viktorf / jwt
Laravel/Symfony JWT 授权服务
1.0.5
2020-07-20 14:19 UTC
Requires
- symfony/http-foundation: ^5.0
Requires (Dev)
- phpunit/phpunit: ^9.2
README
简单的 Laravel/Symfony JWT 授权服务
见https://packagist.org.cn/packages/viktorf/jwt
安装
composer require viktorf/jwt
对于 Laravel,只需将 JWT\JWTServiceProvider 添加到 config/app.php 的正确部分,或者在 AppServiceProvider.php 中注册它,然后使用 AuthenticateWithJWT 中间件。在注册 JWTServiceProvider 之后,您可以发布供应商配置。
php artisan vendor:publish --provider="JWT\JWTServiceProvider" --tag="config"
在 JWT\Service 中的所有类都可以被扩展以扩展它们的逻辑。例如,您可以使用 DI 将中间件构造函数中的 JWTReceiver 和 JWTService 替换为其子类。
使用
$secret = 'some jwt secret'; $token = 'some jwt token'; $service = new \JWT\Service\JWTService($secret); // Callback is not mandatory, you can just skip it in authenticate() call $callback = function (JWT\Service\JWTHeader $header, JWT\Service\JWTPayload $payload) { if (empty($payload->customField)) { throw new \JWT\Exception\JWTException("JWT token is invalid: \$payload->customField is needed"); } log("JWT custom field retrieved: " . $payload->customField); }; try { $this->jwtService->authenticate($token, $callback); } catch (JWT\Exception\JWTException $exception) { throw new HttpException('Access denied', 403, $exception); } catch (Throwable $error) { throw new HttpException('Internal server error', 500, $error); }
扩展
class ExtraJWTPayload extends \JWT\Service\JWTPayload { public string $customField = ''; public function isValid() : bool { if (empty($this->customField)) { return false; } return true; } } class ExtraJWTService extends \JWT\Service\JWTService { protected function getPayloadClass() : string { return ExtraJWTPayload::class; } }