sonnt / cakephp-jwt-auth
使用密码的 cake php jwt auth
Requires
- cakephp/cakephp: ~3.1
- firebase/php-jwt: ~4.0
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-23 16:36:55 UTC
README
包含用于通过 JSON Web Tokens 进行身份验证的 AuthComponent 的 authenticate 类的插件。您可以在此处详细了解 JSON Web Token 规范。
需求
- CakePHP 3.1+
安装
composer require sonnt/cakephp-jwt-auth
用法
在您的应用程序的 config/bootstrap.php
中添加
// In config/bootstrap.php Plugin::load(‘Sonnt/JwtAuth');
或者使用 cake 控制台
./bin/cake plugin load ADmad/JwtAuth
配置
设置 AuthComponent
// In your controller, for e.g. src/Api/AppController.php public function initialize() { parent::initialize(); $this->loadComponent('Auth', [ 'storage' => 'Memory', 'authenticate' => [ ‘Sonnt/JwtAuth.Jwt' => [ 'userModel' => 'Users', 'fields' => [ 'username' => 'id' ], 'parameter' => 'token', // Boolean indicating whether the "sub" claim of JWT payload // should be used to query the Users model and get user info. // If set to `false` JWT's payload is directly returned. 'queryDatasource' => true, ] ], 'unauthorizedRedirect' => false, 'checkAuthIn' => 'Controller.initialize', // If you don't have a login action in your application set // 'loginAction' to false to prevent getting a MissingRouteException. 'loginAction' => false ]); }
工作
身份验证类在两个位置检查令牌
-
HTTP_AUTHORIZATION
环境变量它首先检查是否通过
Authorization
请求头传递了令牌。其值应为Bearer <token>
形式。可以使用选项header
和prefix
分别自定义Authorization
头名称和令牌前缀。注意:某些服务器在设置了
Authorization
头时不会填充$_SERVER['HTTP_AUTHORIZATION']
。因此,您需要确保设置$_SERVER['HTTP_AUTHORIZATION']
或$_ENV['HTTP_AUTHORIZATION']
。例如,对于 Apache,您可以使用以下方法
RewriteEngine On RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
-
使用
parameter
配置指定的查询字符串变量然后,它检查令牌是否存在于查询字符串中。默认变量名称为
token
,可以使用上面显示的parameter
配置进行自定义。
令牌生成
您可以使用此插件所依赖的 firebase/php-jwt 库中的 \Firebase\JWT\JWT::encode()
生成令牌。
有效载荷应该有 "sub"(主题)声明,其值用于查询 Users 模型并找到与 "id" 字段匹配的记录。
您可以将 queryDatasource
选项设置为 false
,以直接返回令牌的有效载荷作为用户信息,而无需查询数据源以匹配用户记录。
进一步阅读
要查看端到端使用示例,请参阅 Bravo Kernel 的这篇博客文章这篇。