davidxu/yii2-jwt

基于 Icobucci 的 JWT 扩展

安装: 4

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:yii2-extension

1.0.0 2023-02-28 05:42 UTC

This package is auto-updated.

Last update: 2024-09-28 09:06:01 UTC


README

此扩展为 JWT 提供了 Yii 框架 2.0 的集成。

目录

  1. 安装
  2. 依赖
  3. 基本用法
    1. 生成公钥和私钥
    2. 作为 Yii 组件使用
    3. 作为 Yii 参数使用
    4. 创建
    5. 从字符串解析
    6. 验证
  4. Yii2 高级模板示例

安装

此软件包可在 Packagist 上获取,您可以使用 Composer 进行安装。

composer require davidxu/yii2-jwt

依赖

  • PHP 8.0+
  • OpenSSL 扩展

基本用法

1. 生成公钥和私钥

公钥/私钥对用于签名和验证传输的 JWT。要生成私钥,请在终端运行此命令

openssl genrsa -out private.key 2048

如果您想为您的私钥提供密码,请改用此命令

openssl genrsa -aes128 -passout pass:_passphrase_ -out private.key 2048

然后从私钥中提取公钥

openssl rsa -in private.key -pubout -out public.key

或者如果提供了私钥生成时的密码,请使用密码

openssl rsa -in private.key -passin pass:_passphrase_ -pubout -out public.key

私钥必须保密(即,不要放在授权服务器的 web-root 中)。

2.1 作为 Yii 组件使用

jwt 组件添加到您的配置文件中,

'components' => [
    'jwt' => [
        'class' => \davidxu\jwt\Jwt::class,
        'privateKey' => __DIR__ . '/../private.key',
        'publicKey' => __DIR__ . '/../public.key',
        // A date/time string. Valid formats are explained in
        // [Date and Time Formats](https://secure.php.net/manual/en/datetime.formats.php)
        'expire_time' => '+2 hour'
    ],
],

2.2 作为 Yii 参数使用

params.php 中添加以下参数

return [
    //...
    'jwt' => [
        'privateKey' => __DIR__ . '/../private.key',
        'publicKey' => __DIR__ . '/../public.key',
        'expire_time' => '+2 hour'
    ],
    //...
];

按以下方式配置 authenticator 行为。

namespace app\controllers;

class ExampleController extends \yii\rest\Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                [
                    'class' => HttpBearerAuth::class,
                ],
            ]
        ];
        return $behaviors;
    }
}

3. 创建

只需使用 getToken 创建/发行新的 JWT 令牌

$jwt = new davidxu\jwt\Jwt();
// OR 
// $jwt = Yii::$app->jwt;
$token = $jwt->getToken([
    'uid' => 12345,
    'app_id' => Yii::$app->id,
]);

echo $token->claims()->get('uid'); // will print "12345"
echo $token->toString();

从字符串解析

使用 parseToken 从 JWT 字符串中解析令牌(使用前面的令牌作为示例)

$jwt = new davidxu\jwt\Jwt();
// OR 
// $jwt = Yii::$app->jwt;
$token = $jwt->parseToken($token);
echo $token->claims()->get('uid'); // will print "12345"

验证

我们可以轻松验证令牌是否有效(使用前面的令牌作为示例)

$jwt = new davidxu\jwt\Jwt();
// OR 
// $jwt = Yii::$app->jwt;
$valid = $jwt->validateToken($token, true, [
    'app_id' => Yii::$app->id,
    ], 'uid'); // return 12345(uid)

Yii2 高级模板示例

更改方法 common\models\User::findIdentityByAccessToken()

public static function findIdentityByAccessToken($token, $type = null): ?Member
{
    // use yii2 components
    $jwt = Yii::$app->jwt;
    // use yii2 params
    $jwt = new \davidxu\jwt\Jwt();
    $jwt->privateKey = Yii::$app->params['jwt']['privateKey'];
    $jwt->publicKey = Yii::$app->params['jwt']['publicKey'];
    $jwt->expire_time = '+2 hour';
    return Member::findOne($jwt->validateToken($jwt->parseToken($token)));
}