algsupport / jwt
为 Yii 2 集成 JWT
Requires
- php: >=8.2
- algsupport/yii2: *
- lcobucci/jwt: ^5.0
This package is auto-updated.
Last update: 2024-09-09 21:34:26 UTC
README
这是 sizeg/yii2-jwt 包的分支
有关版本详情,请参阅 lcobucci/jwt 仓库。
安装
将包添加到您的 composer.json
{ "require": { "algsupport/jwt": "*" } }
并运行 composer update
或运行 composer require algsupport/jwt
基本用法
将 jwt
组件添加到您的配置文件中。
如果您的应用程序既是 JWT 的发行者也是消费者(常见情况,也称为标准版本),则使用 algsupport\jwt\Jwt
组件
[ 'components' => [ 'jwt' => [ 'class' => \algsupport\jwt\Jwt::class, 'signer' => ... // Signer ID, or signer object, or signer configuration, see "Available signers" below 'signingKey' => ... // Secret key string or path to the signing key file, see "Keys" below // ... any additional configuration here ], ], ],
如果您的应用程序只需要一些特殊的 JWT 工具(如验证器或解析器,也称为工具集版本),则使用 algsupport\jwt\JwtTools
组件
[ 'components' => [ 'jwt' => [ 'class' => \algsupport\jwt\JwtTools::class, // ... any additional configuration here ], ], ],
当然,如果您已经使用了标准版本组件,则不需要定义工具集版本组件,因为前者已经提供了所有工具。
如果您对 API JWT 的概念感到困惑,这里有一个 示例,展示了如何快速将所有部分组合起来。
可用的签名者
对称
- HMAC (HS256, HS384, HS512)
非对称
- RSA (RS256, RS384, RS512)
- ECDSA (ES256, ES384, ES512)
- EdDSA (自 3.1.0 版起)
- BLAKE2B (自 3.4.0 版起)
签名者 ID 可作为常量提供(如 Jwt::HS256)。
您也可以提供自己的签名者,无论是 Lcobucci\JWT\Signer
的实例还是将其配置添加到 signers
和 algorithmTypes
并使用其 ID 作为 signer
。
如
lcobucci/jwt
文档中所述:虽然 BLAKE2B 由于其性能而非常棒,但它不是 JWT 标准,不一定由其他库提供。
关于签名者和最小位数的说明
从 lcobucci/jwt 4.2.0
开始,签名者需要最小的密钥长度以确保其得到适当的安全保护,否则将抛出 InvalidKeyProvided
。
密钥
对于对称签名者,需要 signingKey
。对于非对称签名者,您还需要设置 verifyingKey
。密钥可以是简单的字符串、配置数组或 Lcobucci\JWT\Signer\Key
的实例。
配置数组可以是以下形式
[ 'key' => /* key content */, 'passphrase' => /* key passphrase */, 'method' => /* method type */, ]
- key (
algsupport\jwt\Jwt::KEY
) - string,默认''
, - passphrase (
algsupport\jwt\Jwt::PASSPHRASE
) - string,默认''
, - method (
algsupport\jwt\Jwt::METHOD
) - string,默认algsupport\jwt\Jwt::METHOD_PLAIN
,可用的:algsupport\jwt\Jwt::METHOD_PLAIN
,algsupport\jwt\Jwt::METHOD_BASE64
,algsupport\jwt\Jwt::METHOD_FILE
(请参阅 https://lcobucci-jwt.readthedocs.io/en/latest/configuration/)
简单的字符串密钥是以下数组配置的快捷方式
-
key 以
@
或file://
开头[ 'key' => /* given key itself */, 'passphrase' => '', 'method' => \algsupport\jwt\Jwt::METHOD_FILE, ]
在开头检测到
@
假设已提供 Yii 别名,因此它将使用Yii::getAlias()
进行解析。 -
key 既不以
@
开头也不以file://
开头[ 'key' => /* given key itself */, 'passphrase' => '', 'method' => \algsupport\jwt\Jwt::METHOD_PLAIN, ]
发行令牌示例
标准版本
$now = new \DateTimeImmutable(); /** @var \Lcobucci\JWT\Token\UnencryptedToken $token */ $token = Yii::$app->jwt->getBuilder() // Configures the issuer (iss claim) ->issuedBy('http://example.com') // Configures the audience (aud claim) ->permittedFor('http://example.org') // Configures the id (jti claim) ->identifiedBy('4f1g23a12aa') // Configures the time that the token was issued (iat claim) ->issuedAt($now) // Configures the time that the token can be used (nbf claim) ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify('+1 hour')) // Configures a new claim, called "uid" ->withClaim('uid', 1) // Configures a new header, called "foo" ->withHeader('foo', 'bar') // Builds a new token ->getToken( Yii::$app->jwt->getConfiguration()->signer(), Yii::$app->jwt->getConfiguration()->signingKey() ); $tokenString = $token->toString();
工具集版本中的相同内容
$now = new \DateTimeImmutable(); /** @var \Lcobucci\JWT\Token\UnencryptedToken $token */ $token = Yii::$app->jwt->getBuilder() ->issuedBy('http://example.com') ->permittedFor('http://example.org') ->identifiedBy('4f1g23a12aa') ->issuedAt($now) ->canOnlyBeUsedAfter($now->modify('+1 minute')) ->expiresAt($now->modify('+1 hour')) ->withClaim('uid', 1) ->withHeader('foo', 'bar') ->getToken( Yii::$app->jwt->buildSigner(/* signer definition */), Yii::$app->jwt->buildKey(/* signing key definition */) ); $tokenString = $token->toString();
有关更多信息,请参阅 https://lcobucci-jwt.readthedocs.io/en/latest/issuing-tokens/。
解析令牌
/** @var non-empty-string $jwt */ /** @var \Lcobucci\JWT\Token $token */ $token = Yii::$app->jwt->parse($jwt);
请参阅https://lcobucci-jwt.readthedocs.io/en/latest/parsing-tokens/获取更多信息。
验证令牌
您可以验证令牌或对其执行断言(见https://lcobucci-jwt.readthedocs.io/en/latest/validating-tokens/)。
用于验证
/** @var \Lcobucci\JWT\Token | non-empty-string $token */ /** @var bool $result */ $result = Yii::$app->jwt->validate($token);
用于断言
/** @var \Lcobucci\JWT\Token | string $token */ Yii::$app->jwt->assert($token);
您必须提供至少一个约束条件,否则将抛出Lcobucci\JWT\Validation\NoConstraintsGiven
异常。有几种方式提供约束条件
-
直接提供(仅标准版本)
Yii::$app->jwt->getConfiguration()->setValidationConstraints(/* constaints here */);
-
通过组件配置
[ 'validationConstraints' => /* array of instances of Lcobucci\JWT\Validation\Constraint or array of configuration arrays that can be resolved as Constraint instances or anonymous function that can be resolved as array of Constraint instances with signature `function(\algsupport\jwt\Jwt|\algsupport\jwt\JwtTools $jwt)` where $jwt will be an instance of used component */, ]
注意:默认情况下,此包不添加任何约束条件,您必须像上述示例中那样自行配置。
使用组件进行REST认证
在控制器中配置authenticator
行为。
class ExampleController extends Controller { public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => \algsupport\jwt\JwtHttpBearerAuth::class, ]; return $behaviors; } }
有一些特殊选项可用
- jwt - 字符串 组件ID(默认为
'jwt'
),组件配置 数组,或algsupport\jwt\Jwt
或algsupport\jwt\JwtTools
的实例 - auth - 可调用或
null
(默认)- 签名为function (\Lcobucci\JWT\Token $token)
的匿名函数,该函数应返回使用JWT有效负载信息认证的用户身份。如果没有提供$auth,则将调用yii\web\User::loginByAccessToken()
方法。 - throwException - 布尔值(默认
true
)- 是否应抛出异常,例如令牌格式无效。如果有多个认证过滤器(CompositeAuth),则“静默失败”并传递验证过程到复合认证列表中的下一个过滤器可能是有意义的。
有关其他配置选项,请参阅Yii 2 指南。
JWT 用法
请参阅lcobucci/jwt 文档。