ramosisw/cakephp-jwt-claims

CakePHP 插件,用于读取 jwt 令牌上的声明

1.0.0 2018-05-04 17:34 UTC

This package is not auto-updated.

Last update: 2024-09-20 07:52:06 UTC


README

Build Status Coverage Total Downloads License

CakePHP 3.6+ 组件,用于读取授权 JWT 的声明

安装

composer require ramosisw/cakephp-jwt-claims

配置

设置 ClaimsComponent

    // In your controller, for e.g. src/Controller/AppController.php
    public function initialize()
    {
        parent::initialize();
        //Config JWT with ADmad Plugin for more info see https://github.com/ADmad/cakephp-jwt-auth
        $this->loadComponent('Auth', [/*..*/]);
        //Load Claims component
        $this->loadComponent('RamosISW/Jwt.Claims',[
            'claims_key' => 'data', //name where is claims on JWT Payload
            //Wath claims be read
            'data' => [
                'user_id', 'user_email', 'user_name'
            ]
        ]);
    }

工作

读取用户可访问的路由上的声明

    public function index(){
        //read user email sends on token
        $this->log($this->Claims->user_email);
        
        //set claims to use on view
        $this->set('Claims', $this->Claims);
    }

令牌生成

您可以使用该插件依赖的 firebase/php-jwt 库中的 \Firebase\JWT\JWT::encode() 函数来生成令牌。

负载应包含 "sub"(主题)声明,其值用于查询 Users 模型并找到与 "id" 字段匹配的记录。

生成声明

    public function generateToken($user){
        $token = \Firebase\JWT\JWT::encode([
                'sub' => $user['id'],
                'exp' => time() + 604800,
                'data' => [
                    'user_id' => $user['id'],
                    'user_email' => $user['email'],
                    'user_name' => $user['username']
                ]
        ], \Cake\Utility\Security::getSalt());
        
        return $token;
    }