JWT Authentication for WP REST API

Описание

Расширяет API WP REST с помощью проверки подлинности веб-маркеров JSON в качестве метода проверки подлинности.

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

Support and Requests please in Github: https://github.com/Tmeister/wp-api-jwt-auth

REQUIREMENTS

WP REST API V2

This plugin was conceived to extend the WP REST API V2 plugin features and, of course, was built on top of it.

So, to use the wp-api-jwt-auth you need to install and activate WP REST API.

PHP

Minimum PHP version: 7.4.0

PHP HTTP Authorization Header enable

Most of the shared hosting has disabled the HTTP Authorization Header by default.

To enable this option you’ll need to edit your .htaccess file adding the follow

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

WPENGINE

To enable this option you’ll need to edit your .htaccess file adding the follow

See https://github.com/Tmeister/wp-api-jwt-auth/issues/1

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

CONFIGURATION

Configurate the Secret Key

The JWT needs a secret key to sign the token this secret key must be unique and never revealed.

To add the secret key edit your wp-config.php file and add a new constant called JWT_AUTH_SECRET_KEY

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');

You can use a string from here https://api.wordpress.org/secret-key/1.1/salt/

Configurate CORs Support

The wp-api-jwt-auth plugin has the option to activate CORs support.

To enable the CORs Support edit your wp-config.php file and add a new constant called JWT_AUTH_CORS_ENABLE

define('JWT_AUTH_CORS_ENABLE', true);

Finally activate the plugin within your wp-admin.

Namespace and Endpoints

When the plugin is activated, a new namespace is added

/jwt-auth/v1

Also, two new endpoints are added to this namespace

Endpoint | HTTP Verb
/wp-json/jwt-auth/v1/token | POST
/wp-json/jwt-auth/v1/token/validate | POST

USAGE

/wp-json/jwt-auth/v1/token

This is the entry point for the JWT Authentication.

Проверяет учетные данные пользователя, username и password и возвращает токен для использования в будущем запросе API, если проверка подлинности верна или error, если аутентификация завершается с ошибкой.

Sample request using AngularJS

( function() {

  var app = angular.module( 'jwtAuth', [] );

  app.controller( 'MainController', function( $scope, $http ) {

    var apiHost = 'http://yourdomain.com/wp-json';

    $http.post( apiHost + '/jwt-auth/v1/token', {
        username: 'admin',
        password: 'password'
      } )

      .then( function( response ) {
        console.log( response.data )
      } )

      .catch( function( error ) {
        console.error( 'Error', error.data[0] );
      } );

  } );

} )();

Ответ на успех с сервера

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8",
    "user_display_name": "admin",
    "user_email": "admin@localhost.dev",
    "user_nicename": "admin"
}

Ответ на ошибку с сервера

{
    "code": "jwt_auth_failed",
    "data": {
        "status": 403
    },
    "message": "Invalid Credentials."
}

Как только вы получите токен, вы должны сохранить его где-то в своем приложении, например. В cookie или использовать localstorage.

С этого момента вы должны передать этот токен каждому вызову API

Пример вызова с использованием заголовка авторизации с помощью функции AngularJS

app.config( function( $httpProvider ) {
  $httpProvider.interceptors.push( [ '$q', '$location', '$cookies', function( $q, $location, $cookies ) {
    return {
      'request': function( config ) {
        config.headers = config.headers || {};
        //Assume that you store the token in a cookie.
        var globals = $cookies.getObject( 'globals' ) || {};
        //If the cookie has the CurrentUser and the token
        //add the Authorization header in each request
        if ( globals.currentUser && globals.currentUser.token ) {
          config.headers.Authorization = 'Bearer ' + globals.currentUser.token;
        }
        return config;
      }
    };
  } ] );
} );

wp-api-jwt-auth перехватит каждый вызов на сервер и будет искать заголовок авторизации, если присутствует заголовок авторизации, попытается декодировать токен и будет устанавливать пользователя в соответствии с данными, хранящимися в нем.

Если токен действителен, поток вызовов API будет продолжаться, как всегда.

Образцы заголовков

POST /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_s9.B5f-4.1JqM

ERRORS

Если токен недействителен, будет возвращена ошибка, вот несколько примеров ошибок.

Недопустимые учетные данные

[
  {
    "code": "jwt_auth_failed",
    "message": "Invalid Credentials.",
    "data": {
      "status": 403
    }
  }
]

Недействительная подпись

[
  {
    "code": "jwt_auth_invalid_token",
    "message": "Signature verification failed",
    "data": {
      "status": 403
    }
  }
]

Истекший токен

[
  {
    "code": "jwt_auth_invalid_token",
    "message": "Expired token",
    "data": {
      "status": 403
    }
  }
]

/wp-json/jwt-auth/v1/token/validate

Это простая вспомогательная конечная точка для проверки токена; вам нужно будет сделать запрос POST, отправляющий заголовок авторизации.

Валидный Токен Ответа

{
  "code": "jwt_auth_valid_token",
  "data": {
    "status": 200
  }
}

AVAILABLE HOOKS

wp-api-jwt-auth дружелюбен и имеет пять фильтров для переопределения настроек по умолчанию.

jwt_auth_cors_allow_headers

jwt_auth_cors_allow_headers позволяет изменять доступные заголовки, когда включена поддержка CORs.

Значение по умолчанию:

'Access-Control-Allow-Headers, Content-Type, Authorization'

jwt_auth_not_before

The jwt_auth_not_before позволяет вам изменить nbf до того, как будет создан токен.

Значение по умолчанию:

Creation time - time()

jwt_auth_expire

jwt_auth_expire позволяет вам изменить значение exp до создания токена.

Значение по умолчанию:

time() + (DAY_IN_SECONDS * 7)

jwt_auth_token_before_sign

jwt_auth_token_before_sign позволяет вам изменять все данные токена перед их кодировкой и подписью.

Значение по умолчанию

<?php
$token = array(
    'iss' => get_bloginfo('url'),
    'iat' => $issuedAt,
    'nbf' => $notBefore,
    'exp' => $expire,
    'data' => array(
        'user' => array(
            'id' => $user->data->ID,
        )
    )
);

jwt_auth_token_before_dispatch

jwt_auth_token_before_dispatch позволяет вам модифицировать весь массив ответов до отправки его клиенту.

Значение по умолчанию:

<?php
$data = array(
    'token' => $token,
    'user_email' => $user->data->user_email,
    'user_nicename' => $user->data->user_nicename,
    'user_display_name' => $user->data->display_name,
);

jwt_auth_algorithm

The jwt_auth_algorithm allows you to modify the signing algorithm.

Default value:

<?php
$token = JWT::encode(
    apply_filters('jwt_auth_token_before_sign', $token, $user),
    $secret_key,
    apply_filters('jwt_auth_algorithm', 'HS256')
);

// ...

$token = JWT::decode(
    $token,
    new Key($secret_key, apply_filters('jwt_auth_algorithm', 'HS256'))
);

Testing

I’ve created a small app to test the basic functionality of the plugin; you can get the app and read all the details on the JWT-Client Repo

Установка

Использование панели инструментов WordPress

  1. Перейдите к «Добавить новый» в панели плагинов
  2. Найти ‘jwt-authentication-for-wp-rest-api’
  3. Нажмите ‘Установить сейчас’
  4. Активируйте плагин на панели плагинов

Загрузка в админ панель WordPress

  1. Перейдите к «Добавить новый» в панели плагинов
  2. Перейдите в область ‘Загрузки’
  3. Выбрать jwt-authentication-for-wp-rest-api.zip на вашем компьютере
  4. Нажмите ‘Установить сейчас’
  5. Активируйте плагин в панели плагинов

Пожалуйста, прочитайте Как настроить плагин https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Отзывы

13.03.2024
I integrated it with my Flutter app, and it works flawlessly. Here is a little piece of code that I implemented to get User ID and Role: add_filter('jwt_auth_token_before_dispatch', 'add_user_id_and_role_to_jwt_response', 10, 2); function add_user_id_and_role_to_jwt_response($data, $user) { // Aggiungi il campo 'user_id' al JSON della risposta $data['user_id'] = $user->data->ID; // Ottieni il ruolo dell'utente $user_roles = $user->roles; $user_role = !empty($user_roles) ? $user_roles[0] : ''; // Aggiungi il campo 'user_role' al JSON della risposta $data['user_role'] = $user_role; // Restituisci il nuovo array dati modificato return $data; }
30.01.2024
Perfect! This plugin is very easy to install and use. It's also easy to extend and add your own return data.
21.11.2023
It totally works fine. It was challenging to set it up in start but this plugin is helping me to extend the functionalities for my mobile app.
05.09.2023 4 ответа
Hi, The new version (1.3.3) block woocommerce api call. I use OAuth1 for woocommerce so I didn't use jwt for that (only for sign in) but now I have a 403 error. Message: "Authorization header malformed." Can you tell why and how to resolved that ? Thank you.
Посмотреть все 43 отзыва

Участники и разработчики

«JWT Authentication for WP REST API» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:

Участники

Перевести «JWT Authentication for WP REST API» на ваш язык.

Заинтересованы в разработке?

Посмотрите код, проверьте SVN репозиторий, или подпишитесь на журнал разработки по RSS.

Журнал изменений

1.3.4

  • Fix: Skip any type of validation when the authorization header is not Bearer.
  • Feature: Added a setting page to share data and add information about the plugin.

1.3.3

  • Update php-jwt to 6.4.0
  • Fix php warnings (https://github.com/Tmeister/wp-api-jwt-auth/pull/259)
  • Fix the condition where it checks if the request is a REST Request (https://github.com/Tmeister/wp-api-jwt-auth/pull/256)

1.3.2

  • Fix conflicts with other plugins using the same JWT library adding a wrapper namespace to the JWT class.

1.3.1

  • Updating the minimum version of PHP to 7.4
  • Validate the signing algorithm against the supported algorithms @see https://www.rfc-editor.org/rfc/rfc7518#section-3
  • Sanitize the REQUEST_URI and HTTP_AUTHORIZATION values before to use them
  • Use get_header() instead of $_SERVER to get the Authorization header when possible
  • Added typed properties to the JWT_Auth class where possible
  • Along with this release, I release a new simple JWT Client App for testing purposes @see https://github.com/Tmeister/jwt-client

1.3.0

  • Update firebase/php-jwt to 6.3
  • Fix warning, register_rest_route was called incorrectly
  • Allow for Basic Auth, by not attempting to validate Authentication Headers if a valid user has already been determined (see: https://github.com/Tmeister/wp-api-jwt-auth/issues/241)
  • Added a new filter (jwt_auth_algorithm) to allow for customizing the algorithm used for signing the token
  • Props: https://github.com/bradmkjr

1.2.6

  • Cookies && Token compatibility
  • Fix the root problem with gutenberg infinite loops and allow the token validation/generation if the WP cookie exists.
  • More info (https://github.com/Tmeister/wp-api-jwt-auth/pull/138)
  • Props: https://github.com/andrzejpiotrowski

1.2.5

  • Add Gutenberg Compatibility
  • More info (https://github.com/Tmeister/wp-api-jwt-auth/issues/126)

1.2.4

  • Обновление firebase/php-jwt to v5.0.0 ( https://github.com/firebase/php-jwt )
  • Добавить в запрос PHP Tag

1.2.3

  • Fix Max recursion error in WordPress 4.7 #44

1.2.2

  • Add an extra validation to get the Authorization header
  • Increase determine_current_user priority Fix #13
  • Add the user object as parameter in the jwt_auth_token_before_sign hook
  • Improve error message when auth fails #34
  • Tested with 4.6.1

1.2.0

  • Тестировался с версией 4.4.2

1.0.0

  • первый выпуск