JWT Authentication for WP REST API

外掛說明

使用 JSON Web Tokens Authentication 作為認證方法以擴展 WP REST API。

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

需求

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: 5.3.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.

命名空間與端點

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

用法

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

這是 JWT Authentication 的進入點。

Validates the user credentials, username and password, and returns a token to use in a future request to the API if the authentication is correct or error if the authentication fails.

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."
}

一旦你取得 token,你必須在你的應用程式某處儲存它,比如存在 cookie 或使用 localstorage

From this point, you should pass this token to every API call

使用 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;
      }
    };
  } ] );
} );

The wp-api-jwt-auth will intercept every call to the server and will look for the Authorization Header, if the Authorization header is present will try to decode the token and will set the user according with the data stored in it.

假如 token 是合法的,API 呼叫流程將持續下去。

示例標頭

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

錯誤

假如 token 不合法,它就會回傳錯誤,這裡有一些錯誤的例子。

非法的資格

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

非法的簽章

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

過期的 Token

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

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

這是一個用來驗證 token 的簡單端點;你只需要建立一個 POST 請求來傳送 Authorization 標頭。

合法的 Token 回應

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

可用的 HOOKS

The wp-api-jwt-auth is dev friendly and has five filters available to override the default settings.

jwt_auth_cors_allow_headers

The jwt_auth_cors_allow_headers allows you to modify the available headers when the CORs support is enabled.

預設值:

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

jwt_auth_not_before

The jwt_auth_not_before allows you to change the nbf value before the token is created.

預設值:

Creation time - time()

jwt_auth_expire

The jwt_auth_expire allows you to change the value exp before the token is created.

預設值:

time() + (DAY_IN_SECONDS * 7)

jwt_auth_token_before_sign

The jwt_auth_token_before_sign allows you to modify all the token data before to be encoded and signed.

預設值

<?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,
);

安裝方式

使用 WordPress 後台

  1. Navigate to the ‘Add New’ in the plugins dashboard
  2. 搜尋 ‘jwt-authentication-for-wp-rest-api’
  3. 點選「立即安裝」
  4. 在外掛後台啟用此外掛

於 WordPress 後台上傳

  1. Navigate to the ‘Add New’ in the plugins dashboard
  2. Navigate to the ‘Upload’ area
  3. 從你的電腦選擇 jwt-authentication-for-wp-rest-api.zip
  4. 點選「立即安裝」
  5. 在外掛後台啟用此外掛

請詳閱如何設定此外掛 https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

使用者評論

2019 年 8 月 12 日
A very good documentation, authentication for the users with my app in just some simple steps. Extends the WP Rest API, make sure to read very well the documentation, it solves all problems.
2019 年 6 月 27 日
It only shows 3 modules for a vendor. Reviews, Notifications, and enquiry. Where are the other modules? Orders are important, products, reports...etc
2019 年 6 月 5 日
Overall, I like this plugin. I am using it in an upcoming book. An Admin interface to expire tokens and change the expiration time would be nice. but that's not so much a complaint as a wish list. 🙂
閱讀全部 30 則使用者評論

參與者及開發者

以下人員參與了開源軟體〈JWT Authentication for WP REST API〉的開發相關工作。

參與者

將 JWT Authentication for WP REST API 外掛本地化為台灣繁體中文版

對開發相關資訊感興趣?

任何人均可瀏覽程式碼、查看 SVN 存放庫,或透過 RSS 訂閱開發記錄

變更記錄

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 至 v5.0.0 ( https://github.com/firebase/php-jwt )
  • Add Requires 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
  • 於 4.6.1 測試過

1.2.0

  • 於 4.4.2 測試過

1.0.0

  • 初始釋出。