digitaldream / symfony-access-token
Symfony 访问令牌认证包。
1.0.0
2023-11-01 00:56 UTC
Requires
- php: ^8.2
- firebase/php-jwt: ^6.9
- symfony/framework-bundle: 6.3.*
- symfony/security-bundle: 6.3.*
README
安装
composer require digitaldream/symfony-access-token
设置
步骤 1
从供应商文件夹中复制 config/packages/access_token.yaml
步骤 2:
从供应商文件夹中复制 config/routes/access_token.yaml
步骤 3
将这些环境变量添加到您的 .env 文件中
JWT_SECRET="YourSecretKey" JWT_KEY= JWT_ISSUER=localhost:8000 JWT_ALGORITHM=HS256 JWT_EXPIRE_AT='+24 hours'
步骤 4
security: firewalls: api: pattern: ^/api provider: app_user_provider #your user provider stateless: true user_checker: AccessToken\Security\UserChecker access_token: token_handler: AccessToken\Security\AccessTokenHandler failure_handler: AccessToken\Security\AuthenticationFailureHandler access_control: - { path: ^/api, roles: ROLE_USER } # Change this line according to your project USER ROlES
调用登录 API
fetch('/api/login',{ body: { username: 'john@example.com', password: 'YourPassword' } })
您可以创建自己的登录路由。只需移除包路由并使用 AccessToken\Services\CreateAccessTokenService
namespace App\Controller use AccessToken\Entity\AccessToken; use AccessToken\Services\CreateAccessTokenService; use AccessToken\Services\UserCredentialsRequest; use Symfony\Component\HttpFoundation\Request; class LoginController { public function __construct(private CreateAccessTokenService $accessTokenService) {} public function login(Request $request): { //Write your logic //@var AccessToken $accessToken $accessToken= $this->accessTokenService->execute(new UserCredentialsRequest('YourEmail@example.com','YourPassword')) } }
享受吧!
实现用户验证和激活功能
如果用户需要通过电子邮件验证或处于非活动状态,则不会生成访问令牌。只需像下面这样在您的 User
实体上实现 AccessToken\Entity\TokenUserInterface
class User implements UserInterface, PasswordAuthenticatedUserInterface, TokenUserInterface { public function isVerified(): ?bool { // return null if you don't have this functionality return true; } public function isActive(): ?bool { // return null if you don't have this functionality return true; } public function getUserIdentifierValue(): string { return $this->email; } public function getPublicId(): string { // It safe to use a UID (symfony UID) for generating JWT token. Do not expose your internal primary key return (string)$this->id; } }
撤销访问令牌
如果您想撤销特定用户的全部访问令牌,则触发 AccessToken\Events\RevokeAccessTokensEvent
namespace App\Controller; use AccessToken\Events\RevokeAccessTokensEvent; use \Symfony\Component\EventDispatcher\EventDispatcherInterface; class SomeController { public function someAction(EventDispatcherInterface $dispatcher){ //Do something with the User. E.g block or inactive or subscription expired. $dispatcher->dispatch(new RevokeAccessTokensEvent(1),RevokeAccessTokensEvent::NAME) } }