andrewdyer / jwt-auth
一个简单、与框架无关的JSON Web Token认证解决方案
1.0.0
2022-08-22 20:53 UTC
Requires
- php: ^7.2.5
Requires (Dev)
- firebase/php-jwt: ^5.0
- friendsofphp/php-cs-fixer: ^2.16
- nesbot/carbon: ^2.30
- phpunit/phpunit: ^8.5
- symfony/var-dumper: ^5.0
This package is auto-updated.
Last update: 2024-09-23 01:26:30 UTC
README
一个简单、与框架无关的JSON Web Token认证解决方案。
许可证
MIT许可证下发布。完全免费用于私人或商业项目。
安装
composer require andrewdyer/jwt-auth
用法
// Create a new auth provider instance $authProvider = new App\Providers\AuthProvider(); // Create a new jwt provider instance $jwtProvider = new App\Providers\JwtProvider(); // Build up jwt claims $claimsFactory = new Anddye\JwtAuth\ClaimsFactory::build([ 'exp' => 1582243200, // Friday, 21 February 2020 00:00:00 'iat' => 1582193571, // Thursday, 20 February 2020 10:12:51 'iss' => 'https://example.com', 'jti' => 'fVcx9BJHqh', 'nbj' => '1582193571', // Thursday, 20 February 2020 10:12:51 ]); // Bring everything together to create a jwt auth instance $jwtAuth = new JwtAuth($authProvider, $jwtProvider, $claimsFactory);
认证提供者
namespace App\Providers; use Anddye\JwtAuth\Providers\AuthProviderInterface; class AuthProvider implements AuthProviderInterface { public function byCredentials(string $username, string $password) { // TODO: Validate username / password and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject` } public function byId(int $id) { // TODO: Find a user by id and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject` if exists } }
JWT提供者
namespace Anddye\JwtAuth\Tests\Stubs\Providers; use Anddye\JwtAuth\Providers\JwtProviderInterface; class JwtProvider implements JwtProviderInterface { public function decode(string $token) { // TODO: Decode JWT token somehow } public function encode(array $claims): string { // TODO: Encode claims and create a JWT token somehow } }
声明工厂
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory(); $claimsFactory->setExp(1582243200); // Friday, 21 February 2020 00:00:00 $claimsFactory->setIat(1582193571); // Thursday, 20 February 2020 10:12:51 $claimsFactory->setIss('https://example.com'); $claimsFactory->setJti('fVcx9BJHqh'); $claimsFactory->setNbj(1582193571); // Thursday, 20 February 2020 10:12:51
使用凭证尝试
if (!$token = $jwtAuth->attempt($username, $password)) { // TODO: Handle failed attempt with credentials } else { // TODO: Handle successful attempt with credentials }
使用令牌进行认证
if (!$actor = $jwtAuth->authenticate($token)->getActor()) { // TODO: Handle failed authentication with token } else { // TODO: Handle successful authentication with token }
支持
如果您正在使用此包,我很乐意听取您的意见!请在Twitter上与我联系。
需要查看示例吗?请查看此教程,了解如何将此库集成到Slim 3项目中。
发现了一个错误?请使用问题跟踪器报告,或者更好的做法是,分叉仓库并提交一个pull请求。