[WordPress] 外掛分享: JWT Auth – WordPress JSON Web Token Authentication

WordPress 外掛 JWT Auth – WordPress JSON Web Token Authentication 的封面圖片。

前言介紹

  • 這款 WordPress 外掛「JWT Auth – WordPress JSON Web Token Authentication」是 2020-05-04 上架。
  • 目前有 6000 個安裝啟用數。
  • 上一次更新是 2024-05-07,距離現在已有 361 天。
  • 外掛最低要求 WordPress 5.2 以上版本才可以安裝。
  • 外掛要求網站主機運作至少需要 PHP 版本 7.2 以上。
  • 有 22 人給過評分。
  • 論壇上目前有 3 個提問,問題解答率 0%

外掛協作開發者

tha_sun | dominic_ks | contactjavas |

外掛標籤

jwt | jwt auth | json web token | token authentication |

內容簡介

WordPress JSON Web Token Authentication 可讓您通過令牌進行 REST API 認證。它是一個簡單、非複雜且易於使用的外掛程式。這個外掛可能是在 WordPress 中執行 JWT 認證最便利的方法。

支援和提問: WordPress 支援論壇
回報外掛程式錯誤: GitHub 問題跟踪器
Discord 頻道 也可用於更快的回應。

啟用 PHP HTTP 授權標頭
共享主機

大多數共享主機默認禁用 HTTP 授權標頭。

要啟用此選項,您需要編輯 .htaccess 文件,並添加以下內容:

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

WPEngine

要啟用此選項,您需要編輯 .htaccess 文件,並添加以下內容(請參見這個問題):

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

配置
配置 Secret Key

JWT 需要一個密鑰來簽署令牌。這個密鑰必須是唯一的,永遠不能被揭示。

要添加密鑰,編輯您的 wp-config.php 文件,並添加一個名為 JWT_AUTH_SECRET_KEY 的新常數。

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

您可以使用此處的一個字符串。

配置 CORs 支援

此外掛程式有啟用CORs 支援的選項。

要啟用 CORs 支援,請編輯您的 wp-config.php 文件,並添加一個名為 JWT_AUTH_CORS_ENABLE 的新常數

define('JWT_AUTH_CORS_ENABLE', true);

命名空間和端點

在啟用此外掛程式時,會添加一個新命名空間。

/jwt-auth/v1

此外,還會添加兩個新的 POST 端點至此命名空間。

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

請求/生成令牌
/wp-json/jwt-auth/v1/token

要生成令牌,請向此端點提交 POST 請求。使用 username 和 password 作為參數。

它將驗證使用者憑據,如果驗證正確,則返回成功響應,包括令牌,或如果驗證失敗,則返回錯誤響應。

嘗試生成令牌時成功響應的範例:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_credential",
"message": "Credential is valid",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw",
"id": 1,
"email": "[email protected]",
"nicename": "contactjavas",
"firstName": "Bagus Javas",
"lastName": "Heruyanto",
"displayName": "contactjavas"
}
}

嘗試生成令牌時錯誤響應的範例:
{

原文外掛簡介

WordPress JSON Web Token Authentication allows you to do REST API authentication via token. It is a simple, non-complex, and easy to use. This plugin probably is the most convenient way to do JWT Authentication in WordPress.

Support & question: WordPress support forum
Reporting plugin’s bug: GitHub issues tracker
Discord channel also available for faster response.

Upgrading to v3
When updating from v2 to v3, familiarise yourself with its changes to ensure that your site continues to work as expected:
New: Refresh tokens ([docs](https://github.com/usefulteam/jwt-auth#refreshing-the-access-token))
Key changes:

Default JWT access token expiry time has been reduced from 7 days to 10 minutes.
On expiry of a JWT, clients need to retrieve a new access token using the refresh token as described here.
To retain the 7 day expiry time, use the hook jwt_auth_expire.

Removed Whitelist
Key changes:

You no longer need to whitelist REST paths from other plugins with the hook jwt_auth_whitelist. You can remove the hook.
Instead, custom REST API routes should have access requirements specified with the permissions callback when it is registered.
This means that if a route requires authentication, any authentication method can be used and this should reduce conflicts between this and other plugins. See this discussion for further information.

Enable PHP HTTP Authorization Header
Shared Hosts
Most shared hosts have disabled the HTTP Authorization Header by default.
To enable this option you’ll need to edit your .htaccess file by adding the following:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

WPEngine
To enable this option you’ll need to edit your .htaccess file by adding the following (see this issue):
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 be 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
Configurate CORs Support
This 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);

Namespace and Endpoints
When the plugin is activated, a new namespace is added.
/jwt-auth/v1

Also, three new POST endpoints are added to this namespace.
/wp-json/jwt-auth/v1/token
/wp-json/jwt-auth/v1/token/validate
/wp-json/jwt-auth/v1/token/refresh

Requesting/ Generating Token
/wp-json/jwt-auth/v1/token

To generate token, submit a POST request to this endpoint. With username and password as the parameters.
It will validates the user credentials, and returns success response including a token if the authentication is correct or returns an error response if the authentication is failed.
You can use the optional parameter device with the device identifier to let user manage the device access in your profile. If this parameter is empty, it is ignored.
Sample of success response when trying to generate token:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_credential",
"message": "Credential is valid",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw",
"id": 1,
"email": "[email protected]",
"nicename": "contactjavas",
"firstName": "Bagus Javas",
"lastName": "Heruyanto",
"displayName": "contactjavas"
}
}

Sample of error response when trying to generate token:
{
"success": false,
"statusCode": 403,
"code": "invalid_username",
"message": "Unknown username. Try again or check your email address.",
"data": []
}

Once you get the token, you must store it somewhere in your application. It can be:
– using cookie
– or using localstorage
– or using a wrapper like localForage or PouchDB
– or using local database like SQLite or Hive
– or your choice based on app you develop 😉
Then you should pass this token as Bearer Authentication header to every API call. The header format is:
Authorization: Bearer your-generated-token

and here’s an example:
"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw";

The jwt-auth will intercept every call to the server and will look for the authorization header, if the authorization header is present, it will try to decode the token and will set the user according with the data stored in it.
If the token is valid, the API call flow will continue as always.
Validating Token
You likely don’t need to validate the token your self. The plugin handle it for you like explained above.
But if you want to test or validate the token manually, then send a POST request to this endpoint (don’t forget to set your Bearer Authorization header):
/wp-json/jwt-auth/v1/token/validate

Valid Token Response:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_token",
"message": "Token is valid",
"data": []
}

Refreshing the Access Token
For security reasons, third-party applications that are integrating with your authentication server will not store the user’s username and password. Instead they will store the refresh token in a user-specific storage that is only accessible for the user. The refresh token can be used to re-authenticate as the same user and generate a new access token.
When authenticating with username and password as the parameters to /wp-json/jwt-auth/v1/token, a refresh token is sent as a cookie in the response.
/wp-json/jwt-auth/v1/token

To generate new access token using the refresh token, submit a POST request to the token endpoint together with the refresh_token cookie.
Use the optional parameter device with the device identifier to associate the token with that device.
If the refresh token is valid, then you receive a new access token in the response.
By default, each access token expires after 10 minutes.
/wp-json/jwt-auth/v1/token/refresh

To generate new refresh token using the refresh token, submit a POST request to the token refresh endpoint together with the refresh_token cookie.
Use the optional parameter device with the device identifier to associate the refresh token with that device.
If the refresh token is valid, then you receive a new refresh token as a cookie in the response.
By default, each refresh token expires after 30 days.
Refresh Token Rotation
Whenever you are authenticating afresh or refreshing the refresh token, only the last issued refresh token remains valid. All previously issued refresh tokens can no longer be used.
This means that a refresh token cannot be shared. To allow multiple devices to authenticate in parallel without losing access after another device re-authenticated, use the parameter device with the device identifier to associate the refresh token only with that device.
curl -F device="abc-def" -F username=myuser -F password=mypass /wp-json/jwt-auth/v1/token

curl -F device="abc-def" -b "refresh_token=123.abcdef..." /wp-json/jwt-auth/v1/token

curl -F device="abc-def" -b "refresh_token=123.abcdef..." /wp-json/jwt-auth/v1/token/refresh

Errors
If the token is invalid an error will be returned. Here are some samples of errors:
No Secret Key
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_config",
"message": "JWT is not configured properly.",
"data": []
}

No HTTP_AUTHORIZATION Header
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_no_auth_header",
"message": "Authorization header not found.",
"data": []
}

Bad Iss
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_iss",
"message": "The iss do not match with this server.",
"data": []
}

Invalid Signature
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_invalid_token",
"message": "Signature verification failed",
"data": []
}

Incomplete Payload
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_request",
"message": "User ID not found in the token.",
"data": []
}

User Not Found
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_user_not_found",
"message": "User doesn't exist",
"data": []
}

Expired Token
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_invalid_token",
"message": "Expired token",
"data": []
}

Obsolete Token
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_obsolete_token",
"message": "Token is obsolete",
"data": []
}

Invalid Refresh Token
{
"success": false,
"statusCode": 401,
"code": "jwt_auth_invalid_refresh_token",
"message": "Invalid refresh token",
"data": []
}

Obsolete Refresh Token
{
"success": false,
"statusCode": 401,
"code": "jwt_auth_obsolete_refresh_token",
"message": "Refresh token is obsolete",
"data": []
}

Expired Refresh Token
{
"success": false,
"statusCode": 401,
"code": "jwt_auth_expired_refresh_token",
"message": "Refresh token has expired",
"data": []
}

Available Filter Hooks
JWT Auth is developer friendly and has some 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.
Default Value:
'X-Requested-With, Content-Type, Accept, Origin, Authorization'

Usage example:
/**
* Change the allowed CORS headers.
*
* @param string $headers The allowed headers.
* @return string The allowed headers.
*/
add_filter(
'jwt_auth_cors_allow_headers',
function ( $headers ) {
// Modify the headers here.
return $headers;
}
);

jwt_auth_iss
The jwt_auth_iss allows you to change the iss value before the payload is encoded to be a token.
Default Value:
get_bloginfo( 'url' )

Usage example:
/**
* Change the token issuer.
*
* @param string $iss The token issuer.
* @return string The token issuer.
*/
add_filter(
'jwt_auth_iss',
function ( $iss ) {
// Modify the "iss" here.
return $iss;
}
);

jwt_auth_not_before
The jwt_auth_not_before allows you to change the nbf value before the payload is encoded to be a token.
Default Value:
// Creation time.
time()

Usage example:
/**
* Change the token's nbf value.
*
* @param int $not_before The default "nbf" value in timestamp.
* @param int $issued_at The "iat" value in timestamp.
*
* @return int The "nbf" value.
*/
add_filter(
'jwt_auth_not_before',
function ( $not_before, $issued_at ) {
// Modify the "not_before" here.
return $not_before;
},
10,
2
);

jwt_auth_expire
The jwt_auth_expire allows you to change the value exp before the payload is encoded to be a token.
Default Value:
time() + (DAY_IN_SECONDS * 7)

Usage example:
/**
* Change the token's expire value.
*
* @param int $expire The default "exp" value in timestamp.
* @param int $issued_at The "iat" value in timestamp.
*
* @return int The "nbf" value.
*/
add_filter(
'jwt_auth_expire',
function ( $expire, $issued_at ) {
// Modify the "expire" here.
return $expire;
},
10,
2
);

jwt_auth_refresh_expire
The jwt_auth_refresh_expire filter hook allows you to change the expiration date of the refresh token.
Default Value:
time() + (DAY_IN_SECONDS * 30)

Usage example:
/**
* Change the refresh token's expiration time.
*
* @param int $expire The default expiration timestamp.
* @param int $issued_at The current time.
*
* @return int The custom refresh token expiration timestamp.
*/
add_filter(
'jwt_auth_refresh_expire',
function ( $expire, $issued_at ) {
// Modify the "expire" here.
return $expire;
},
10,
2
);

jwt_auth_alg
The jwt_auth_alg allows you to change the supported signing algorithm for your application.
Default Value:
'HS256'

Usage example:
/**
* Change the token's signing algorithm.
*
* @param string $alg The default supported signing algorithm.
* @return string The supported signing algorithm.
*/
add_filter(
'jwt_auth_alg',
function ( $alg ) {
// Change the signing algorithm here.
return $alg;
}
);

jwt_auth_payload
The jwt_auth_payload allows you to modify all the payload / token data before being encoded and signed.
Default value:
get_bloginfo('url'),
'iat' => $issued_at,
'nbf' => $not_before,
'exp' => $expire,
'data' => array(
'user' => array(
'id' => $user->ID,
)
)
);

Usage example:
/**
* Modify the payload/ token's data before being encoded & signed.
*
* @param array $payload The default payload
* @param WP_User $user The authenticated user.
* .
* @return array The payload/ token's data.
*/
add_filter(
'jwt_auth_payload',
function ( $payload, $user ) {
// Modify the payload here.
return $payload;
},
10,
2
);

jwt_auth_valid_credential_response
The jwt_auth_valid_credential_response allows you to modify the valid credential response when generating a token.
Default value:
true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_credential',
'message' => __( 'Credential is valid', 'jwt-auth' ),
'data' => array(
'token' => $token,
'id' => $user->ID,
'email' => $user->user_email,
'nicename' => $user->user_nicename,
'firstName' => $user->first_name,
'lastName' => $user->last_name,
'displayName' => $user->display_name,
),
);

Usage example:
/**
* Modify the response of valid credential.
*
* @param array $response The default valid credential response.
* @param WP_User $user The authenticated user.
* .
* @return array The valid credential response.
*/
add_filter(
'jwt_auth_valid_credential_response',
function ( $response, $user ) {
// Modify the response here.
return $response;
},
10,
2
);

jwt_auth_valid_token_response
The jwt_auth_valid_token_response allows you to modify the valid token response when validating a token.
Default value:
true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_token',
'message' => __( 'Token is valid', 'jwt-auth' ),
'data' => array(),
);

Usage example:
/**
* Modify the response of valid token.
*
* @param array $response The default valid token response.
* @param WP_User $user The authenticated user.
* @param string $token The raw token.
* @param array $payload The token data.
* .
* @return array The valid token response.
*/
add_filter(
'jwt_auth_valid_token_response',
function ( $response, $user, $token, $payload ) {
// Modify the response here.
return $response;
},
10,
4
);

jwt_auth_extra_token_check
The jwt_auth_extra_token_check allows you to add extra criterias to validate the token. If empty, has no problem to proceed. Use empty value to bypass the filter. Any other value will block the token access and returns response with code jwt_auth_obsolete_token.
Default value:
''

Usage example:
/**
* Modify the validation of token. No-empty values block token validation.
*
* @param array $response An empty value ''.
* @param WP_User $user The authenticated user.
* @param string $token The raw token.
* @param array $payload The token data.
* .
* @return array The valid token response.
*/
add_filter(
'jwt_auth_extra_token_check',
function ( $response, $user, $token, $payload ) {
// Modify the response here.
return $response;
},
10,
4
);

Credits
PHP-JWT from firebase
JWT Authentication for WP REST API
Devices utility by pesseba
The awesome maintainers and contributors

各版本下載點

  • 方法一:點下方版本號的連結下載 ZIP 檔案後,登入網站後台左側選單「外掛」的「安裝外掛」,然後選擇上方的「上傳外掛」,把下載回去的 ZIP 外掛打包檔案上傳上去安裝與啟用。
  • 方法二:透過「安裝外掛」的畫面右方搜尋功能,搜尋外掛名稱「JWT Auth – WordPress JSON Web Token Authentication」來進行安裝。

(建議使用方法二,確保安裝的版本符合當前運作的 WordPress 環境。


1.4.2 | 2.0.0 | 2.1.0 | 2.1.1 | 2.1.2 | 2.1.3 | 2.1.4 | 2.1.5 | 2.1.6 | 3.0.2 |

延伸相關外掛(你可能也想知道)

  • WordPress REST API Authentication 》WordPress REST API 預設是鬆散的端點,駭客可以通過這些端點遠程控制您的網站。 您不希望駭客可以透過 WordPress 登錄和 WordPress 註冊或任何其他端點來獲...。
  • Simple REST API Authenticaton with WooCommerce Credentials 》介紹我們新的 Simple REST API Authentication WordPress 外掛程式,是協調您的網站與外部應用程序間無間接的整合方案。, 此外掛程式讓您可以使用基本認證方...。
  • Simple JWT Auth 》總結:, 這是一個使用 JSON Web Tokens 來擴展 WordPress REST API 的外掛,可提供穩固的身份驗證和授權,讓外部應用程式安全地存取和管理 WordPress 數據,非...。

文章
Filter
Apply Filters
Mastodon