![图片[1]-深入解析在 WordPress 中实现 JWT 身份验证的完整指南-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/uploads/2024/07/2024072307462094.png)
JWT (JSON Web Token) is a lightweight, self-contained, token for authentication and authorization that encodes user information (e.g., user ID, roles, permissions, etc.) into a JSON object and then digitally signs it to generate a signed token. In this article, we will introduce the concept and structure of JWT, and explain how to implement JWT generation and validation in WordPress.
What is JWT?
JWT is a security mechanism commonly used for stateless RESTful API authentication. It allows the server to validate the passed tokens, thus guaranteeing the authenticity of the user's identity. Since JWT is encrypted as it is transmitted between the client and the server, it prevents information from being tampered with.
Structure of JWT
![图片[2]-深入解析在 WordPress 中实现 JWT 身份验证的完整指南-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/uploads/2024/07/2024072307543861.png)
JWT consists of three parts: Header, Payload and Signature, which are connected by dots (.) to form a complete JWT, as shown below. ), which are connected by dots to form a complete JWT, as shown below:
header.payload.signature
- Header
Header is a JSON object containing two properties:alg(signature algorithm) and typ(Common signature algorithms are HS256, RS256, etc.) Common signature algorithms are HS256, RS256, etc. The Header will be encoded with Base64Url to produce the following string:
{
"alg": "HS256",
"typ": "JWT"
}
- Payload
A Payload is also a JSON object containing user information and other business data. The declaration can be predefined (e.g. iss,exp,sub The Payload is also Base64Url encoded to produce the following string:
{
"sub": "1234567890",
"name": "John Doe".
"iat": 1516239022
}
Predefined fields include:
iss(issuer): the person who issued itsub(subjectaud(audienceexp(expiration time): expiration timenbf(Not Before): Time of entry into forceiat(Issued At): Time of issuancejti(JWT ID): Unique Identifier
- Signature
Signature is used to ensure the integrity and security of the JWT. It encrypts the Header, Payload and a key (Secret) with a signature algorithm. An example is shown below:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
The generated signature is appended to the end of the JWT to form the complete JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Implementing JWT in WordPress
Implementing JSON Web Token (JWT) authentication in WordPress involves the following steps:
Step 1: Install the JWT Authentication Plugin
- Log in to your WordPress admin backend.
- Navigate to plug-in (software component) > Installation of new plug-insThe
- look for sth. JWT Authentication for WP REST APIThe
- Install and activate the plugin.
![图片[3]-深入解析在 WordPress 中实现 JWT 身份验证的完整指南-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/uploads/2024/07/2024072307590722.png)
Step 2: Configure the plug-in
- After activating the plugin, navigate to Settings > JWT AuthenticationThe
- On the Settings page, you need to configure the following options:
- Secret Key: This is the key used to sign the JWT. You can find the key in the
wp-config.phpAdd the following line of code to the file to set the key:define('JWT_AUTH_SECRET_KEY', 'your-secret-key'); - Enable CORS: Enable this option if you have a need for cross-domain requests.
- Secret Key: This is the key used to sign the JWT. You can find the key in the
Step 3: Configure the .htaccess file
in the root directory of your website .htaccess The following rule is added to the file:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(. *)
RewriteRule ^(. *) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>
Step 4: Generate JWT
The following is a function for generating a JWT:
function wpjam_generate_jwt($payload, $secret='', $header=[]){
// 无法生成没有设置过期时间的 JWT
if(empty($payload['exp'])){
return false;
}
$header = wp_parse_args($header, [
'alg' => 'HS256',
'typ' => 'JWT'
]);
if($header['alg'] == 'HS256'){
$header = base64_urlencode(wpjam_json_encode($header));
$payload = base64_urlencode(wpjam_json_encode($payload));
$jwt = $header.'.'.$payload;
$secret = $secret ?: wp_salt();
return $jwt.'.'.base64_urlencode(hash_hmac('sha256', $jwt, $secret, true));
}
}
The above code starts with JSON encoding and URL-safe Base64 encoding of the Header and Payload. The key (Secret) for generating the signature is generated using the WordPress default salt function if it is empty. Finally, the Header, Payload, and generated signature are linked together by the dot (.) ) to form a complete JWT.
Step 5: Authenticate the JWT
The process of validating the JWT is the generated inverse process, which is implemented as follows:
function wpjam_verify_jwt($token, $secret=''){
$tokens = explode('.' , $token);
if(count($tokens) ! = 3){
return false; }
}
list($header, $payload, $sign) = $tokens;
$jwt = $header.'. .$payload; $jwt = $header.
$secret = $secret ? : wp_salt();
$header = wpjam_json_decode(base64_urldecode($header));
$payload = wpjam_json_decode(base64_urldecode($payload));
if(empty($header['alg']) || $header['alg'] ! = 'HS256'){
return false; }
}
if(!hash_equals(base64_urlencode(hash_hmac('sha256', $jwt, $secret, true)), $sign)){
return false;
}
// Authentication fails if the issuance time is greater than the current server time
if(isset($payload['iat']) && $payload['iat'] > time()){
return false.
}
// Do not accept the Token for processing until this nbf time
if(isset($payload['nbf']) && $payload['nbf'] > time()){
return false;
}
// No expiration time set, or expiration time less than current server time validation fails
if(empty($payload['exp']) || $payload['exp'] < time()){
return false.
}
return $payload.
}
The code above first splits the JWT into Header, Payload, and Signature segments by using dot (.) The code above first splits the JWT into Header, Payload and Signature segments by dot (.), then performs URL-secure Base64 decoding and JSON decoding on the Header and Payload. The signature is finally verified against the signed key. If the signature is valid and the token has not expired, the Payload data is returned.
Step 6: Base64 URL Encoding and Decoding Functions
URL-safe Base64 encoding and decoding functions used in the above process base64_urlencode respond in singing base64_urldecode It also needs to be defined:
function base64_urlencode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64_urldecode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
![图片[4]-深入解析在 WordPress 中实现 JWT 身份验证的完整指南-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/uploads/2024/06/2024061301281171.png)
summarize
pass (a bill or inspection etc) wpjam_generate_jwt respond in singing wpjam_verify_jwt These two functions, which can be implemented in WordPress JWT JWT provides a secure, stateless way to authenticate users and is becoming increasingly popular in modern Web development.
Link to this article:https://www.361sale.com/en/14448/The article is copyrighted and must be reproduced with attribution.




















![表情[wozuimei]-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/themes/zibll/img/smilies/wozuimei.gif)
![表情[baoquan]-光子波动网 | WordPress教程、Elementor教程与故障修复](https://www.361sale.com/wp-content/themes/zibll/img/smilies/baoquan.gif)

No comments