teamgantt / juhwit
验证来自 AWS Cognito 的 JWTs
Requires
- php: >=7.0
- codercat/jwk-to-pem: ^0.0.3
- firebase/php-jwt: ^6.0
Requires (Dev)
- kahlan/kahlan: ^4.7
This package is not auto-updated.
Last update: 2024-09-16 21:16:04 UTC
README
验证来自 AWS Cognito 的 JWT's
使用方法
Juhwit 随带一些接口及其默认实现。
Juhwit 提供的主要服务是 JwtDecoder
,它由互补的 CognitoClaimVerifier
组成。
<?php use TeamGantt\Juhwit\JwtDecoder; use TeamGantt\Juhwit\Models\UserPool; use TeamGantt\Juhwit\CognitoClaimVerifier; // Create a UserPool to pass to the CognitoClaimVerifier $poolId = 'some pool id from cognito'; $clientIds = ['some client id from cognito']; $region = 'us-east-2'; // we need some public keys in the form of a jwk (accessible via cognito) $jwk = json_decode(file_get_contents('path/to/jwk.json'), true); $pool = new UserPool($poolId, $clientIds, $region, $jwk); $verifier = new CognitoClaimVerifier($pool); $decoder = new JwtDecoder($verifier); // If all is valid we will get a token back - otherwise a TokenException is thrown $token = $decoder->decode($someTokenFromARequest);
需要额外的声明
可能需要令牌具有某些声明。
如果您想要求声明,例如 custom:foo
或 custom:user
,您可以通过向 decode
方法提供一个第二个参数来要求这些声明。
<?php use TeamGantt\Juhwit\JwtDecoder; $decoder = new JwtDecoder($verifier); $token = $decoder->decode($someTokenFromARequest, ['custom:foo', 'custom:user']);
也可能需要声明值是特定值。
use TeamGantt\Juhwit\JwtDecoder; $decoder = new JwtDecoder($verifier); $token = $decoder->decode($someTokenFromARequest, ['custom:user', 'token_use' => 'id']);
请注意,Token
的实例将自行对所需声明进行检查。有关更多信息,请参阅 TeamGantt\Juhwit\Models\Token::getClaimsErrors()。
自定义令牌创建
Juhwit 为 id 令牌和访问令牌提供了默认实现。在 jwt 与公钥验证后,声明和用户提供的 $requiredClaims
将传递到 TokenFactoryInterface
的 create
方法。
默认的 CognitoTokenFactory
将根据提供的令牌类型返回 IdToken
或 AccessToken
。当构建 JwtDecoder
时,可以将自定义的 TokenFactoryInterface
传递给构造函数。
此工厂可用于创建自定义令牌 - 唯一的要求是 create
方法返回一个 TokenInterface
。工厂抛出的任何 TokenException
都将被捕获,并且令牌将被视为无效。
利用 docker
Juhwit 针对 PHP 7.4.11 进行测试和开发。此项目结合使用 docker 和 direnv 来保持一致的环境。要利用 direnv,请 cd
进入 juhwit 项目目录并运行以下命令:
$ docker build -t juhwit:dev .
$ direnv allow
这将使您的当前终端进入使用 docker 化的 php 和 composer 二进制文件的环境。您可以使用它们像平常一样,例如
$ php -v
$ composer list
运行测试
$ composer test