usefulteam / jwt-auth
JWT Auth
Requires
Requires (Dev)
- php: >=7.4
- ext-curl: *
- ext-json: *
- guzzlehttp/guzzle: ^7.8.1
- phpunit/phpunit: ^9.5
This package is not auto-updated.
Last update: 2024-09-20 09:52:06 UTC
README
WordPress JWT (JSON Web Token) Authentication 允许您通过令牌进行 REST API 身份验证。这是一个简单、非复杂且易于使用的。
这个插件可能是 WordPress 中进行 JWT 身份验证的最便捷方式。从WordPress 插件页面下载。
- 支持与问题:WordPress 支持论坛
- 报告插件错误:GitHub 问题跟踪器
- 还有Discord 频道可供使用。
要求
PHP
最低 PHP 版本:7.2
启用 PHP HTTP 授权头
共享主机
大多数共享主机默认禁用了 HTTP 授权头。
要启用此选项,您需要通过添加以下内容来编辑您的 .htaccess 文件
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
WPEngine
要启用此选项,您需要通过添加以下内容来编辑您的 .htaccess 文件(参见 此问题)
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
安装
通过 WordPress 管理区域
- 从 WordPress 管理区域,转到插件 -> 添加新插件
- 搜索 JWT Auth
- 安装它
- 轻松配置它(见下文配置)
- 然后激活它
手动下载
- 从WordPress 插件页面下载插件
- 将其上传到您的 wp-content 目录
- 轻松配置它(见下文配置)
- 从管理区域的 插件 菜单中激活它
配置
配置密钥
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
此外,还向此命名空间添加了三个新的端点。
请求/生成令牌
/wp-json/jwt-auth/v1/token
要生成令牌,向此端点提交 POST 请求。参数为 username
和 password
。
它将验证用户凭据,如果身份验证正确,则返回包含令牌的成功响应,如果身份验证失败,则返回错误响应。
您可以使用可选参数 device
和设备标识符来让用户管理您的个人资料中的设备访问。如果此参数为空,则忽略。
尝试生成令牌时的成功响应示例
{ "success": true, "statusCode": 200, "code": "jwt_auth_valid_credential", "message": "Credential is valid", "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw", "id": 1, "email": "contactjavas@gmail.com", "nicename": "contactjavas", "firstName": "Bagus Javas", "lastName": "Heruyanto", "displayName": "contactjavas" } }
尝试生成令牌时的错误响应示例
{ "success": false, "statusCode": 403, "code": "invalid_username", "message": "Unknown username. Try again or check your email address.", "data": [] }
一旦你获取了令牌,就必须将其存储在你的应用程序的某个地方。可以是
- 使用 cookie
- 或者使用 localstorage
- 或者使用类似 localForage 或 PouchDB 的封装器
- 或者使用本地数据库如 SQLite 或 Hive
- 或者根据你开发的应用来选择 ;)
然后你应该将此令牌作为 Bearer 认证 头部传递给每个 API 调用。头部格式为
Authorization: Bearer 你的生成令牌
下面是一个例子
"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw";
jwt-auth 将拦截每个对服务器的调用,并查找授权头部,如果存在授权头部,它将尝试解码令牌并根据其中存储的数据设置用户。
如果令牌有效,API 调用流程将像往常一样继续。
验证令牌
你可能 不需要 自己验证令牌。插件会为你处理,如上所述。
但如果你想手动测试或验证令牌,则发送一个 POST 请求到该端点(别忘了设置你的 Bearer 授权 头部)
/wp-json/jwt-auth/v1/token/validate
有效的令牌响应
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_token",
"message": "Token is valid",
"data": []
}
刷新访问令牌
出于安全考虑,与你的身份验证服务器集成的第三方应用程序不会存储用户的用户名和密码。相反,它们将在只有用户可以访问的用户特定存储中存储刷新令牌。刷新令牌可用于重新认证为同一用户并生成新的访问令牌。
当使用 username
和 password
作为 /wp-json/jwt-auth/v1/token
的参数进行身份验证时,刷新令牌将以 cookie 的形式发送在响应中。
/wp-json/jwt-auth/v1/token
要使用刷新令牌生成新的访问令牌,请向令牌端点提交带有 refresh_token
cookie 的 POST 请求。
使用可选参数 device
与设备标识符关联令牌与该设备。
如果刷新令牌有效,则你将在响应中获得新的访问令牌。
默认情况下,每个访问令牌在 10 分钟后过期。
/wp-json/jwt-auth/v1/token/refresh
要使用刷新令牌生成新的刷新令牌,请向令牌刷新端点提交带有 refresh_token
cookie 的 POST 请求。
使用可选参数 device
与设备标识符关联刷新令牌与该设备。
如果刷新令牌有效,则你将在响应中获得新的刷新令牌作为 cookie。
默认情况下,每个刷新令牌在 30 天后过期。
刷新令牌轮换
每次你重新进行身份验证或刷新刷新令牌时,只有最后发布的刷新令牌是有效的。所有先前发布的刷新令牌都无法再使用。
这意味着刷新令牌不能共享。为了允许多个设备并行进行身份验证而不在另一个设备重新认证后失去访问权限,请使用设备标识符的参数 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
错误响应
如果令牌无效,将返回错误。以下是错误的一些示例
没有密钥
{ "success": false, "statusCode": 500, "code": "jwt_auth_bad_config", "message": "JWT is not configured properly.", "data": [] }
没有 HTTP_AUTHORIZATION 头部
{ "success": false, "statusCode": 401, "code": "jwt_auth_no_auth_header", "message": "Authorization header not found.", "data": [] }
iss 错误
{ "success": false, "statusCode": 401, "code": "jwt_auth_bad_iss", "message": "The iss do not match with this server.", "data": [] }
无效签名
{ "success": false, "statusCode": 401, "code": "jwt_auth_invalid_token", "message": "Signature verification failed", "data": [] }
不完整的有效载荷
{ "success": false, "statusCode": 401, "code": "jwt_auth_bad_request", "message": "User ID not found in the token.", "data": [] }
找不到用户
{ "success": false, "statusCode": 401, "code": "jwt_auth_user_not_found", "message": "User doesn't exist", "data": [] }
令牌过期
{ "success": false, "statusCode": 401, "code": "jwt_auth_invalid_token", "message": "Expired token", "data": [] }
过时的令牌
{ "success": false, "statusCode": 401, "code": "jwt_auth_obsolete_token", "message": "Token is obsolete", "data": [] }
无效的刷新令牌
{ "success": false, "statusCode": 401, "code": "jwt_auth_invalid_refresh_token", "message": "Invalid refresh token", "data": [] }
过时的刷新令牌
{ "success": false, "statusCode": 401, "code": "jwt_auth_obsolete_refresh_token", "message": "Refresh token is obsolete", "data": [] }
刷新令牌过期
{ "success": false, "statusCode": 401, "code": "jwt_auth_expired_refresh_token", "message": "Refresh token has expired", "data": [] }
可用的过滤钩子
JWT认证易于开发者使用,并提供了一些过滤器以覆盖默认设置。
jwt_auth_cors_allow_headers
jwt_auth_cors_allow_headers
允许您修改启用 CORS 支持时可用的高级别。
默认值
'X-Requested-With, Content-Type, Accept, Origin, Authorization'
使用示例
/** * 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_authorization_header
jwt_auth_authorization_header 允许您修改用于验证令牌的 Authorization 头键。当服务器已经使用 'Authorization' 键用于其他认证方法时非常有用。
默认值
'HTTP_AUTHORIZATION'
使用示例
/** * Modify the response of Authorization header key. * * @param string $header The Authorization header key. * . * @return string The Authorization header key. */ add_filter( 'jwt_auth_authorization_header', function ( $header ) { // Modify the response here. return $header; }, 10, 1 );
jwt_auth_iss
jwt_auth_iss 允许您更改在将有效负载编码为令牌之前要编码的 iss 值。
默认值
get_bloginfo( 'url' )
使用示例
/** * 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
jwt_auth_not_before
允许您更改在将有效负载编码为令牌之前要编码的 nbf 值。
默认值
// Creation time.
time()
使用示例
/** * 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
jwt_auth_expire
允许您更改在将有效负载编码为令牌之前要编码的 exp 值。
默认值
time() + (MINUTE_IN_SECONDS * 10)
使用示例
/** * 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
jwt_auth_refresh_expire
过滤器钩子允许您更改刷新令牌的过期日期。
默认值
time() + (DAY_IN_SECONDS * 30)
使用示例
/** * 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
jwt_auth_alg
允许您更改应用支持的签名 算法。
默认值
'HS256'
使用示例
/** * 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
jwt_auth_payload
允许您在编码和签名之前修改所有有效负载/令牌数据。
默认值
<?php $token = array( 'iss' => get_bloginfo('url'), 'iat' => $issued_at, 'nbf' => $not_before, 'exp' => $expire, 'data' => array( 'user' => array( 'id' => $user->ID, ) ) );
使用示例
/** * 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
jwt_auth_valid_credential_response
允许您在生成令牌时修改有效的凭证响应。
默认值
<?php $response = array( 'success' => 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, ), );
使用示例
/** * 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
jwt_auth_valid_token_response 允许您在验证令牌时修改有效的令牌响应。
默认值
<?php $response = array( 'success' => true, 'statusCode' => 200, 'code' => 'jwt_auth_valid_token', 'message' => __( 'Token is valid', 'jwt-auth' ), 'data' => array(), );
使用示例
/** * 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
jwt_auth_extra_token_check 允许您添加额外的标准以验证令牌。如果为空,则无问题继续进行。使用空值以跳过过滤器。任何其他值将阻止令牌访问,并返回带有代码 jwt_auth_obsolete_token
的响应。
默认值
''
使用示例
/** * 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 );
自动化测试
您可以运行端到端测试以确认 API 是否正常工作。
$ URL=https://example.local USERNAME=myuser PASSWORD=mypass composer run test > ./vendor/bin/phpunit PHPUnit 9.5.13 by Sebastian Bergmann and contributors. ............. 13 / 13 (100%) Time: 00:12.377, Memory: 6.00 MB OK (13 tests, 110 assertions)
致谢
- 来自 Firebase 的 PHP-JWT
- JWT Authentication for WP REST API。此 JWT-Auth 插件是对 JWT Authentication for WP REST API 插件的“复制然后修改”。
- pesseba 的设备实用程序
- 优秀的维护者 和 贡献者
许可证
保持此插件活跃并维护
您可以通过以下方式帮助我们保持此插件活跃并继续维护它:
谢谢!