[WordPress] 外掛分享: Simple JWT Auth

WordPress 外掛 Simple JWT Auth 的封面圖片。

前言介紹

  • 這款 WordPress 外掛「Simple JWT Auth」是 2024-10-30 上架。
  • 目前尚無安裝啟用數,是個很新的外掛。如有要安裝使用,建議多測試確保功能沒問題!
  • 上一次更新是 2024-11-17,距離現在已有 168 天。
  • 外掛最低要求 WordPress 5.2 以上版本才可以安裝。
  • 外掛要求網站主機運作至少需要 PHP 版本 7.4 以上。
  • 尚未有人給過這款外掛評分。
  • 還沒有人在論壇上發問,可能目前使用數不多,還沒有什麼大問題。

外掛協作開發者

sayandey18 |

外掛標籤

jwt | jwt auth | rest-api | authentication | json web token |

內容簡介

總結:
這是一個使用 JSON Web Tokens 來擴展 WordPress REST API 的外掛,可提供穩固的身份驗證和授權,讓外部應用程式安全地存取和管理 WordPress 數據,非常適合建立無前端 CMS 解決方案。

要在 WordPress 支援論壇獲得支援和提出問題,可以到 GitHub 上該外掛的問題追蹤器回報相關問題。

問題與答案:
1. 如何啟用 PHP HTTP授權標頭?
- 大多數共享主機預設情況下禁用了HTTP授權標頭,要啟用此功能需要修改.htaccess 檔案,加入指定的代碼。

2. Simple JWT Auth 外掛需要什麼來加密和解密金鑰?
- 外掛需要一個32個字符長的加密簽名金鑰來加密和解密秘密金鑰、私鑰和公鑰。

3. 如何請求/產生一個新的令牌?
- 發送POST請求到`/wp-json/auth/v1/token`端點,使用用戶名和密碼作為參數。根據驗證結果,會返回包含令牌的成功回應或錯誤回應。

4. 如何在應用程式中儲存令牌?
- 可以使用 Cookie、localstorage、localForage 或 PouchDB 等方式,根據你開發應用程式的需求選擇合適的方式。

原文外掛簡介

Extends the WordPress REST API using JSON Web Tokens for robust authentication and authorization.
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between two parties.
It provides a secure and reliable way to access and manage WordPress data from external applications, making it ideal for building headless CMS solutions.

Support & question: WordPress support forum
Reporting plugin’s bug: GitHub issues tracker

Plugins GitHub Repo https://github.com/sayandey18/simple-jwt-auth
Enable PHP HTTP Authorization Header
HTTP Authorization is a mechanism that allows clients to provide credentials to servers, thereby gaining access to protected resources. This is typically achieved by sending a special header, the Authorization header, in the HTTP request.
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 adding the follow:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

Configuration
Simple JWT Auth plugin needs a Signing Key to encrypt and decrypt the secret key, private key, and public key. This signing key must be exact 32 charecter long and never be revealed.
To add the signing key edit your wp-config.php file and add a new constant called SIMPLE_JWT_AUTH_ENCRYPT_KEY
define( 'SIMPLE_JWT_AUTH_ENCRYPT_KEY', 'your-32-char-signing-key' );

Generate a 32 charecter key from here: https://string-gen.netlify.app
Here is the sample response if the encryption key is not configured in wp-config.php file.
{
"code": "simplejwt_bad_encryption_key",
"message": "Encryption key is not configured properly.",
"data": {
"status": 403
}
}

REST Endpoints
When the plugin is activated, a new namespace is added.
/auth/v1

Also, two new endpoints are added to this namespace.
*/wp-json/auth/v1/token | POST
*/wp-json/auth/v1/token/validate | POST

Requesting/Generating Token
To generate a new 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.
curl --location 'https://example.com/wp-json/auth/v1/token' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "wordpress_username",
"password": "wordpress_password"
}'

Sample of success response
{
"code": "simplejwt_auth_credential",
"message": "Token created successfully",
"data": {
"status": 200,
"id": "2",
"email": "[email protected]",
"nicename": "sayan_dey",
"display_name": "Sayan Dey",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciO........."
}
}

Sample of error response
{
"code": "simplejwt_invalid_username",
"message": "Error: The username admin_user is not registered on this site. If you are unsure of your username, try your email address instead.",
"data": {
"status": 403
}
}

Once you get the token, you can store it somewhere in your application:

using Cookie
or using localstorage
or using a wrapper like localForage or PouchDB
or using local database like SQLite
or your choice based on app you develop

Then you should pass this token as Bearer Authentication header to every API call.
Authorization: Bearer your-generated-token

Here is an example to create WordPress post using JWT token authentication.
curl --location 'https://example.com/wp-json/wp/v2/posts' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciO.........' \
--data '{
"title": "Dummy post through API",
"content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"status": "publish",
"tags": [
4,
5,
6
]
}'

Plugin’s middleware intercepts every request to the server, checking for the presence of the Authorization header. If the header is found, it attempts to decode the JWT token contained within.
Upon successful decoding, the middleware extracts the user information stored in the token and authenticates the user accordingly, ensuring that only authorized requests are processed.
Validating Token
This is a helper endpoint to validate a token. You only will need to make a POST request sending the Bearer Authorization header.
curl --location --request POST 'https://example.com/wp-json/auth/v1/token/validate' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciO.........'

Sample of success response
{
"code": "simplejwt_valid_token",
"message": "Token is valid",
"data": {
"status": 200
}
}

REST Errors
If the token is invalid an error will be returned, here are some samples of errors.
Invalid Username
{
"code": "simplejwt_invalid_username",
"message": "Error: The username admin is not registered on this site. If you are unsure of your username, try your email address instead.",
"data": {
"status": 403
}
}

Invalid Password
{
"code": "simplejwt_incorrect_password",
"message": "Error: The password you entered for the username tiyasha_das is incorrect. Lost your password?",
"data": {
"status": 403
}
}

Invalid Signature
{
"code": "simplejwt_invalid_token",
"message": "Signature verification failed",
"data": {
"status": 403
}
}

Invalid Token
{
"code": "simplejwt_invalid_token",
"message": "Syntax error, malformed JSON",
"data": {
"status": 403
}
}

Expired Token
{
"code": "simplejwt_invalid_token",
"message": "Expired token",
"data": {
"status": 403
}
}

No Authorization
{
"code": "simplejwt_no_auth_header",
"message": "Authorization header not found",
"data": {
"status": 403
}
}

Bad Authorization
{
"code": "simplejwt_bad_auth_header",
"message": "Authorization header malformed",
"data": {
"status": 400
}
}

Wrong Algorithm Token
{
"code": "simplejwt_invalid_token",
"message": "Incorrect key for this algorithm",
"data": {
"status": 403
}
}

Unsupported Algorithm
{
"code": "simplejwt_unsupported_algorithm",
"message": "Unsupported algorithm see https://tinyurl.com/uf4ns6fm",
"data": {
"status": 403
}
}

Bad Configuration
{
"code": "simplejwt_bad_config",
"message": "JWT is not configured properly, please contact the admin",
"data": {
"status": 403
}
}

Bad Encryption Key
{
"code": "simplejwt_bad_encryption_key",
"message": "Encryption key is not configured properly.",
"data": {
"status": 403
}
}

Invalid Encryption Key Length
{
"code": "simplejwt_invalid_enckey_length",
"message": "Encryption key must be exactly 32 characters long",
"data": {
"status": 400
}
}

Available Hooks
Simple JWT Auth is a developer-friendly plugin. It has various filter hooks available to override the default settings.
simplejwt_cors_allow_headers
The simplejwt_cors_allow_headers allows you to modify the available headers when the Cross-Origin Resource Sharing (CORS) support is enabled.
Default value:
'Access-Control-Allow-Headers, Content-Type, Authorization'

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

simplejwt_auth_iss
The simplejwt_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("simplejwt_auth_iss", function ($iss) {
// Modify the "iss" here.
return $iss;
});

simplejwt_not_before
The simplejwt_not_before allows you to change the nbf value before the payload is encoded to be a token.
Default value:
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(
"simplejwt_not_before",
function ($not_before, $issued_at) {
// Modify the "not_before" here.
return $not_before;
},
10,
2,
);

simplejwt_auth_expire
The simplejwt_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(
"simplejwt_auth_expire",
function ($expire, $issued_at) {
// Modify the "expire" here.
return $expire;
},
10,
2,
);

simplejwt_payload_before_sign
The simplejwt_payload_before_sign allows you to modify all the payload data before being encoded and signed.
Default value:
$payload = [
"iss" => $this->simplejwt_get_iss(),
"iat" => $issued_at,
"nbf" => $not_before,
"exp" => $expire,
"data" => [
"user" => [
"id" => $user->data->ID,
],
],
];

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

simplejwt_token_before_dispatch
The simplejwt_token_before_dispatch allows you to modify the token response before to dispatch it to the client.
Default value:
$data = new WP_REST_Response(
[
"code" => "simplejwt_auth_credential",
"message" => JWTNotice::get_notice("auth_credential"),
"data" => [
"status" => 200,
"id" => $user->data->ID,
"email" => $user->data->user_email,
"nicename" => $user->data->user_nicename,
"display_name" => $user->data->display_name,
"token" => $token,
],
],
200,
);

Usage example:
/**
* Modify the JWT response before dispatch.
*
* @param WP_REST_Response $data The token response data.
* @param WP_User $user The user object for whom the token is being generated.
* @return WP_REST_Response Modified token response data.
*/
add_filter(
"simplejwt_token_before_dispatch",
function ($data, $user) {
// Modify the response data.
if ($user instanceof WP_User) {
}
return $data;
},
10,
2,
);

Credits

WordPress REST API
php-jwt by Firebase

各版本下載點

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

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


1.0.0 | 1.0.1 | 1.0.2 | trunk |

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

  • Limit Login Attempts 》此外掛可限制正常登入及使用驗證 cookies 登入的次數。, WordPress 預設允許使用者無限次數嘗試登入,無論是透過登入頁面或是傳送特殊 cookies 皆可。這讓密...。
  • InfiniteWP Client 》InfiniteWP 可讓使用者從自己的伺服器管理無限數量的 WordPress 網站。, 主要功能:, , 自行託管系統:位於您自己的伺服器上,完全受您控制, 一鍵更新所有網站...。
  • WPS Limit Login 》繁體中文, 限制通過登錄頁面和使用權限Cookie可能的登錄嘗試次數。, WordPress 默認情況下允許通過登錄頁面或發送特殊 Cookie 的方式進行無限制的登錄嘗試。...。
  • Two-Factor 》在「使用者」→「您的個人檔案」下的「雙因素認證選項」部分,啟用和設定一個或多個雙因素認證提供者:, , 電子郵件代碼, 時間同步一次性密碼(TOTP), FIDO通...。
  • WP-Members Membership Plugin 》8211; allows you to restrict file downloads to registered users only, with customizable download links., MailChimp Integration – integrates W...。
  • Google Authenticator 》WordPress 的 Google Authenticator 外掛使用 Google Authenticator App 為 Android/iPhone/Blackberry 手機提供雙因素驗證。, 如果您有安全意識,您可能已經...。
  • Login by Auth0 》這個外掛會以 Auth0 為基礎,取代標準 WordPress 登入表單,具有以下功能:, , 通用身分驗證, , 超過 30 個社交登入提供者, 企業連接 (ADFS、Active Director...。
  • WP Limit Login Attempts 》Limit Login Attempts 是一款可保護登錄安全,防止暴力破解攻擊的 WordPress 插件。暴力破解攻擊通常採用最簡單的方式來獲得網站控制權:一遍遍地嘗試輸入帳...。
  • Login for Google Apps 》Google應用登錄允許現有的WordPress使用者使用Google進行帳戶驗證來登錄您的網站以實現安全認證。這意味著,如果他們已經登入Gmail,他們可以通過WordPress登...。
  • Application Passwords 》⚠️ 重要提示:此外掛已合併至 WordPress 5.6 核心,不需要單獨安裝。 查看整合指南→, 使用應用程式密碼進行身份驗證,而不必直接提供用戶的密碼。相反,為每...。
  • WP SAML Auth 》 , 使用打包的 OneLogin SAML library 或者可选的安装 SimpleSAMLphp,WP SAML Auth 插件提供 WordPress 的 SAML 身份验证。OneLogin 提供了一个 SAML 身份验...。
  • Email Login 》使用電子郵件地址作為登入 WordPress 的識別名稱,代替使用者名稱。, 因為 WordPress 規定電子郵件地址必須在系統中唯一,所以使用它作為登入識別名稱是個好...。
  • Log in with Google 》這是一個極簡化的外掛,讓您的使用者可以使用他們的 Google 帳戶登入 WordPress 應用程式,不再需要記住笨重的密碼!, 初始設置, , , 如果尚未存在,請從 Goo...。
  • Active Directory Integration / LDAP Integration 》展示 | 文檔 | 特性 | 插件 | 聯繫我們, Active Directory 整合 / LDAP 整合 Intranet 登入的外掛程式 可以讓您使用其 Active Directory/LDAP 憑證身分驗證您...。
  • Duo Two-Factor Authentication 》Duo Security 提供雙因素認證服務,以保護帳戶免受劫持和資料竊取。使用 Duo 外掛,您可以在幾分鐘內輕鬆地將 Duo 雙因素認證添加到您的 WordPress 網站中!,...。

文章
Filter
Apply Filters
Mastodon