前言介紹
- 這款 WordPress 外掛「JWT Authentication for WP REST API」是 2015-09-04 上架。
- 目前有 50000 個安裝啟用數。
- 上一次更新是 2025-04-22,距離現在已有 11 天。
- 外掛最低要求 WordPress 4.2 以上版本才可以安裝。
- 外掛要求網站主機運作至少需要 PHP 版本 7.4.0 以上。
- 有 48 人給過評分。
- 論壇上目前有 3 個提問,問題解答率 0%
外掛協作開發者
tmeister |
外掛標籤
jwt | login | wp-api | wp-json | json web authentication |
內容簡介
此外掛使用 JSON Web Tokens (JWT) 做為驗證方式,擴充了 WP REST API 。JSON Web Tokens 是一種開放且具有行業標準的方法,用來在兩方之間安全地傳遞聲明。
支援與請求請至 Github:https://github.com/Tmeister/wp-api-jwt-auth
需求
WP REST API V2
此外掛是為了擴充 WP REST API V2(plugin) 的功能所開發的。使用 wp-api-jwt-auth 前,需要先安裝並啟用 WP REST API 。
PHP
最低 PHP 版本為 5.3.0。
啟用 PHP HTTP 授權標頭
大部分共用主機因為限制而將 HTTP 授權標頭關閉,啟用此選項,您需要編輯 .htaccess 檔案,並加入以下內容:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
WP ENGINE
啟用此選項,您需要編輯 .htaccess 檔案,並加入以下內容:
請參閱 https://github.com/Tmeister/wp-api-jwt-auth/issues/1
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
設定
設定 Secret Key
JWT 需要 Secret Key 做為簽署權杖的密鑰,此密鑰必須是唯一且永遠不會公開的。想要添加 Secret Key ,請編輯 wp-config.php 檔案,加入新的常數 JWT_AUTH_SECRET_KEY :
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
可前往以下位置取得字串 https://api.wordpress.org/secret-key/1.1/salt/
設定 CORs 支援
wp-api-jwt-auth 外掛提供啟用 CORs (跨源資源共用) 支援的選項。啟用此功能,請編輯 wp-config.php 檔案,加入新的常數 JWT_AUTH_CORS_ENABLE :
define('JWT_AUTH_CORS_ENABLE', true);
最後啟用外掛於您的 wp-admin 。
命名空間與端點
啟用外掛後,會新增一個新的命名空間:
/jwt-auth/v1
除此之外,還會新增兩個端點至該命名空間:
端點 | HTTP 動詞
/wp-json/jwt-auth/v1/token | POST
/wp-json/jwt-auth/v1/token/validate | POST
使用方式
/wp-json/jwt-auth/v1/token
這是 JWT 驗證的入口點:驗證使用者認證,例如使用者名稱和密碼,如果驗證正確,會傳回令牌,以在未來的 API 請求中使用;如果驗證失敗,則會傳回錯誤訊息。
使用 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.ey
原文外掛簡介
This plugin seamlessly extends the WP REST API, enabling robust and secure authentication using JSON Web Tokens (JWT). It provides a straightforward way to authenticate users via the REST API, returning a standard JWT upon successful login.
Key features of this free version include:
Standard JWT Authentication: Implements the industry-standard RFC 7519 for secure claims representation.
Simple Endpoints: Offers clear /token and /token/validate endpoints for generating and validating tokens.
Configurable Secret Key: Define your unique secret key via wp-config.php for secure token signing.
Optional CORS Support: Easily enable Cross-Origin Resource Sharing support via a wp-config.php constant.
Developer Hooks: Provides filters (jwt_auth_expire, jwt_auth_token_before_sign, etc.) for customizing token behavior.
JSON Web Tokens are an open, industry standard method for representing claims securely between two parties.
For users requiring more advanced capabilities such as multiple signing algorithms (RS256, ES256), token refresh/revocation, UI-based configuration, or priority support, consider checking out JWT Authentication PRO.
Support and Requests: Please use GitHub Issues. For priority support, consider upgrading to PRO.
JWT Authentication PRO
Elevate your WordPress security and integration capabilities with JWT Authentication PRO. Building upon the solid foundation of the free version, the PRO version offers advanced features, enhanced security options, and a streamlined user experience:
Easy Configuration UI: Manage all settings directly from the WordPress admin area.
Token Refresh Endpoint: Allow users to refresh expired tokens seamlessly without requiring re-login.
Token Revocation Endpoint: Immediately invalidate specific tokens for enhanced security control.
Customizable Token Payload: Add custom claims to your JWT payload to suit your specific application needs.
Granular CORS Control: Define allowed origins and headers with more precision directly in the settings.
Rate Limiting: Protect your endpoints from abuse with configurable rate limits.
Audit Logs: Keep track of token generation, validation, and errors.
Priority Support: Get faster, dedicated support directly from the developer.
Upgrade to JWT Authentication PRO Today!
Free vs. PRO Comparison
Here’s a quick look at the key differences:
Basic JWT Authentication: Included (Free), Included (PRO)
Token Generation: Included (Free), Included (PRO)
Token Validation: Included (Free), Included (PRO)
Token Refresh Mechanism: Not Included (Free), Included (PRO)
Token Revocation: Not Included (Free), Included (PRO)
Token Management Dashboard: Not Included (Free), Included (PRO)
Analytics & Monitoring: Not Included (Free), Included (PRO)
Geo-IP Identification: Not Included (Free), Included (PRO)
Rate Limiting: Not Included (Free), Included (PRO)
Detailed Documentation: Basic (Free), Comprehensive (PRO)
Developer Tools: Not Included (Free), Included (PRO)
Premium Support: Community via GitHub (Free), Priority Direct Support (PRO)
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 shared hosting providers 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
For WPEngine hosting, you’ll need to edit your .htaccess file by adding the following:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
See https://github.com/Tmeister/wp-api-jwt-auth/issues/1 for more details.
CONFIGURATION
Configure 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 generate a secure key from: https://api.wordpress.org/secret-key/1.1/salt/
Looking for easier configuration? JWT Authentication PRO allows you to manage all settings through a simple admin UI.
Configure CORS Support
The wp-api-jwt-auth plugin has the option to activate CORS support.
To enable 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
Need more functionality? JWT Authentication PRO includes additional endpoints for token refresh and revocation.
USAGE
/wp-json/jwt-auth/v1/token
This is the entry point for JWT Authentication.
It validates the user credentials, username and password, and returns a token to use in future requests to the API if the authentication is correct, or an error if 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]);
});
});
})();
Success Response From The Server
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8",
"user_display_name": "admin",
"user_email": "[email protected]",
"user_nicename": "admin"
}
Error Response From The Server
{
"code": "jwt_auth_failed",
"data": {
"status": 403
},
"message": "Invalid Credentials."
}
Once you get the token, you must store it somewhere in your application, e.g., in a cookie or using localStorage.
From this point, you should pass this token with every API call.
Sample Call Using The Authorization Header With 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 plugin 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 to the data stored in it.
If the token is valid, the API call flow will continue as normal.
Sample Headers
POST /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_s9.B5f-4.1JqM
ERRORS
If the token is invalid, an error will be returned. Here are some sample errors:
Invalid Credentials
[
{
"code": "jwt_auth_failed",
"message": "Invalid Credentials.",
"data": {
"status": 403
}
}
]
Invalid Signature
[
{
"code": "jwt_auth_invalid_token",
"message": "Signature verification failed",
"data": {
"status": 403
}
}
]
Expired Token
[
{
"code": "jwt_auth_invalid_token",
"message": "Expired token",
"data": {
"status": 403
}
}
]
Need advanced error tracking? JWT Authentication PRO offers enhanced error tracking and monitoring capabilities.
/wp-json/jwt-auth/v1/token/validate
This is a simple helper endpoint to validate a token. You only need to make a POST request with the Authorization header.
Valid Token Response
{
"code": "jwt_auth_valid_token",
"data": {
"status": 200
}
}
AVAILABLE HOOKS
The wp-api-jwt-auth plugin is developer-friendly and provides five filters to override the default settings.
jwt_auth_cors_allow_headers
The jwt_auth_cors_allow_headers filter allows you to modify the available headers when CORS support is enabled.
Default Value:
'Access-Control-Allow-Headers, Content-Type, Authorization'
jwt_auth_not_before
The jwt_auth_not_before filter allows you to change the nbf value before the token is created.
Default Value:
Creation time - time()
jwt_auth_expire
The jwt_auth_expire filter allows you to change the exp value before the token is created.
Default Value:
time() + (DAY_IN_SECONDS * 7)
jwt_auth_token_before_sign
The jwt_auth_token_before_sign filter allows you to modify all token data before it is encoded and signed.
Default Value:
$token = array(
'iss' => get_bloginfo('url'),
'iat' => $issuedAt,
'nbf' => $notBefore,
'exp' => $expire,
'data' => array(
'user' => array(
'id' => $user->data->ID,
)
)
);
Want easier customization? JWT Authentication PRO allows you to add custom claims directly through the admin UI.
jwt_auth_token_before_dispatch
The jwt_auth_token_before_dispatch filter allows you to modify the response array before it is sent to the client.
Default Value:
$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 filter allows you to modify the signing algorithm.
Default value:
$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 in the JWT-Client Repo.
各版本下載點
- 方法一:點下方版本號的連結下載 ZIP 檔案後,登入網站後台左側選單「外掛」的「安裝外掛」,然後選擇上方的「上傳外掛」,把下載回去的 ZIP 外掛打包檔案上傳上去安裝與啟用。
- 方法二:透過「安裝外掛」的畫面右方搜尋功能,搜尋外掛名稱「JWT Authentication for WP REST API」來進行安裝。
(建議使用方法二,確保安裝的版本符合當前運作的 WordPress 環境。
1.0.0 | 1.2.0 | 1.2.1 | 1.2.2 | 1.2.3 | 1.2.4 | 1.2.5 | 1.2.6 | 1.3.0 | 1.3.1 | 1.3.2 | 1.3.3 | 1.3.4 | 1.3.5 | 1.3.6 | 1.3.7 | trunk |
延伸相關外掛(你可能也想知道)
ACF to REST API 》此 WordPress 外掛在WordPress REST API中提供了Advanced Custom Fields的端點, 詳細資訊請參閱GitHub:https://github.com/airesvsg/acf-to-rest-api/。
REST API Log 》這是一款針對 WordPress REST API v2 的外掛程式,可記錄 REST API 的請求和回應紀錄。, 功能包括:, , WordPress 管理頁面,用於查看和搜尋日誌條目, API 端...。
REST API Meta Support 》此外掛可以自動將 WordPress REST API 的文章(/wp-json/wp/v2/posts)或頁面(/wp-json/wp/v2/pages) POST 中的 meta 欄位所包含的元數據自動存儲於建立的...。
WP API Menus 》此外掛擴充了 WordPress JSON REST API,並提供 WordPress 註冊選單的新路徑。, 現在提供的新路徑如下:, , /menus 所有已註冊選單的清單。, /menus/
Password Reset with Code for WordPress REST API 》這是一個簡單的外掛程式,可以在 WordPress REST API 中使用代碼添加重設密碼功能。 此過程是一個兩步驟的流程:, , 用戶請求重設密碼。一個四位數的代碼將發...。
WP REST API – Pure Taxonomies 》現在您不需要額外的請求來獲取分類信息(term_id、name、slug、term_group、term_taxonomy_id、taxonomy、description、parent、count、filter),其ID已經在...。
ACF to WP-API 》此外掛能夠將文章、頁面、自定義文章類型、評論、附件和分類法詞彙中的所有 ACF 欄位,整合進 WP-API 輸出中的「acf」鍵下。此外,此外掛亦會新增一個/option...。
WP REST API Cache 》啟用 WordPress REST API 快取並提升應用程式的速度。, 詳情請參閱 GitHub:http://github.com/airesvsg/wp-rest-api-cache。
WP API Yoast SEO 》在一般的文章或頁面請求中返回 Yoast 文章或頁面的元數據。將元數據儲存在回傳資料的 yoast_meta 欄位中。。
SearchWP API 》此外掛可透過 WordPress REST API 和 SearchWP 執行進階搜尋。, 為 WordPress REST API 新增了一個端點,以透過 SearchWP 進行搜尋 - SearchWP 是改善 WordPr...。
WP Custom REST API Generator 》WP Custom REST API Generator 外掛提供一個介面在 WordPress 的管理面板中,允許使用者控制所有可用的文章類型的作者資訊、特色圖片、自訂欄位和分類法是否...。
REST API Multiple Post Types 》若 WordPress 外掛中的文章類型使用 WordPress REST API(在聲明文章類型時,show_in_rest 必須設為 true),則可以使用 /wp/v2/posts 進行查詢。, 查詢範例,...。
User Data Fields For JWT Authentication 》,原文描述並未完成,缺少後續內容。。
WP REST API – All Terms 》這個外掛將會新增一個單獨的 WordPress REST API(v2)端點,其中包含所有可用的術語(所有已使用的類別、標籤和自訂分類法)。, 當您需要在應用程式中建立一...。
WP-REST-API Menus 》此外掛新增了「路徑」或「終點」至 WP REST API,以 JSON 格式檢索選單資料。, 此為 Claudio La Barbera (http://www.claudiolabarbera.com) 的 WP-REST-API ...。