decodelabs / cipher
用于与 JWTs 交互的工具和系统
v0.1.3
2024-08-22 02:55 UTC
Requires
- php: ^8.1
- decodelabs/archetype: ^0.3
- decodelabs/coercion: ^0.2.8
- decodelabs/glitch-support: ^0.4.5
- firebase/php-jwt: ^6.9
Requires (Dev)
- decodelabs/dovetail: ^0.2.0
- decodelabs/harvest: ^0.3
- decodelabs/phpstan-decodelabs: ^0.6.7
README
用于与 JWTs 交互的工具和系统
Cipher 提供了一个用于处理 JWTs 的集成工具套件,包括创建和验证令牌的简单接口,以及用于与 Harvest、Greenleaf 或任何其他 PSR-15 兼容中间件栈一起使用的中间件集合。
在 DecodeLabs 博客 上获取新闻和更新。
安装
通过 Composer 安装
composer require decodelabs/cipher
用法
### Codec
Codec
类提供了对 JWTs 编码和解码的方法。该类需要一个 DecodeLabs\Cipher\Config
实例传递给构造函数 - 我们为此提供了一个默认的 Dovetail
实现,但如果你愿意,也可以使用自己的。
配置定义了使用的密钥和算法。
use DecodeLabs\Cipher\Codec; use DecodeLabs\Dovetail; $codec = new Codec( Dovetail::load('Cipher') ); $payload = $codec->decode($token);
有效载荷
Payload
接口定义了一个简单包装 JWT 有效载荷数据的包装器,支持 ArrayAccess
。工厂将实例化一个 Generic
有效载荷用于未识别的发行者,但是可以创建并使用特定发行者的扩展实现,从而提供对自定义声明数据的正式访问。
// $payload['iss'] = 'https://abcdefg.supabase.co/auth/v1' // $payload instance of DecodeLabs\Cipher\Payload\Supabase $email = $payload->getEmail(); $provider = $payload->getProvider();
中间件
Cipher 为与 Harvest 或 Greenleaf 或任何其他 PSR-15 兼容中间件栈一起使用提供了一系列中间件。
在你的 PSR-15 栈中使用中间件时,Cipher 将尝试从请求中加载 JWT,如果成功,将解码后的有效载荷设置为请求上的 jwt.payload
属性。
$payload = $request->getAttribute('jwt.payload');
如果使用 Greenleaf
,则可以通过 Slingshot
自动将有效载荷注入到你的操作中(以下示例使用 Supabase
有效载荷)
use DecodeLabs\Cipher\Payload\Supabase; use DecodeLabs\Greenleaf\Action; use DecodeLabs\Greenleaf\Action\ByMethodTrait; use DecodeLabs\Harvest; use DecodeLabs\Harvest\Response; class MySecureAction implements Action { use ByMethodTrait; public const Middleware = [ 'Jwt' => [ 'required' => true ] ]; public function get( Supabase $payload ): Response { return Harvest::json([ 'email' => $payload->getEmail() ]); } }
许可
Cipher 在 MIT 许可证下发布。有关完整的许可证文本,请参阅 LICENSE。