quankim/cakephp-jwt-auth

此包的最新版本(1.1)没有可用的许可证信息。

QuanKim/JwtAuth 插件,适用于 CakePHP 3

安装: 177

依赖: 1

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

类型:cakephp-plugin

1.1 2016-07-03 18:29 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:53:04 UTC


README

Build Status Coverage Total Downloads License

安装

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方法是

composer require quankim/cakephp-jwt-auth

使用方法

在您的应用配置的 config/bootstrap.php 中添加

// In config/bootstrap.php
Plugin::load('QuanKim/JwtAuth');

或使用 cake 的控制台

./bin/cake plugin load QuanKim/JwtAuth

迁移 AuthToken 表

./bin/cake migrations migrate -p QuanKim/JwtAuth

配置

设置 AuthComponent

    // In your controller, for e.g. src/Api/AppController.php
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Auth', [
            'storage' => 'Memory',
            'authenticate', [
                'QuanKim/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
        ]);
    }

设置 Config/app.php 在文件底部添加

'AuthToken'=>[
        'expire'=>3600
    ]

工作

认证类在两个位置检查令牌

  • HTTP_AUTHORIZATION 环境变量

    它首先检查是否通过 Authorization 请求头传递了令牌。值应该是 Bearer <token> 的形式。可以使用 headerprefix 选项分别自定义 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" 字段的记录。

示例

$access_token = JWT::encode([
                'sub' => $user['id'],
                'exp' =>  time() + $expire
            ],Security::salt());
$refresh_token = JWT::encode([
                'sub' => $user['id'],
                'ref'=>time()
            ],Security::salt());
$authToken = $this->Users->AuthToken->newEntity();
$authToken->user_id = $user['id'];
$authToken->access_token = $access_token;
$authToken->refresh_token = $refresh_token;
$this->Users->AuthToken->save($authToken);
$this->set([
    'success' => true,
    'data' => [
        'access_token' => $access_token,
        'refresh_token'=> $refresh_token,
        'id'=>$user['id'],
        'username'=> $user['username'],
        'email'=> $user['email']
    ],
    '_serialize' => ['success', 'data']
]);

您可以将 queryDatasource 选项设置为 false,直接返回令牌的有效负载作为用户信息,而无需查询数据源以找到匹配的用户记录。

进一步阅读

有关端到端使用示例,请参阅 Bravo Kernel 的这篇博客文章:如何将 JWT 认证添加到 CakePHP 3 REST API 中