我正在 symfony 中進行 JWT 令牌認證。登錄后,我已經獲得了一個有效期為 5 分鐘的有效令牌。
我需要的是Bearer TOKEN其他路線的強制通行證。
我在郵遞員中嘗試過,沒有授權,它給了我結果。
我怎樣才能使路由強制使用令牌。
這些是代碼,我試過了。
令牌驗證器.php
class TokenAuthenticator extends AbstractGuardAuthenticator
{
public function __construct(
private string $jwtSecret,
private EntityManagerInterface $entityManager
) {
}
public function start(Request $request, AuthenticationException $authException = null): JsonResponse
{
$data = [
'message' => 'Authentication Required'
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supports(Request $request): bool
{
return $request->headers->has('Authorization');
}
public function getCredentials(Request $request)
{
return $request->headers->get('Authorization');
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
try {
$credentials = str_replace('Bearer ', '', $credentials);
$decodedJwt = (array) JWT::decode(
$credentials,
new Key($this->jwtSecret, 'HS256')
);
return $this->entityManager
->getRepository(User::class)
->findOneBy([
'username' => $decodedJwt['user'],
]);
} catch (Exception $exception) {
throw new AuthenticationException($exception->getMessage());
}
}
public function checkCredentials($credentials, UserInterface $user): bool
{
return true;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse
{
return new JsonResponse([
'message' => $exception->getMessage()
], Response::HTTP_UNAUTHORIZED);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)
{
return;
}
public function supportsRememberMe(): bool
{
return false;
}
}
安全.yaml
security:
enable_authenticator_manager: true
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
encoders:
App\Entity\User:
algorithm: bcrypt
providers:
user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: user_provider
pattern: ^/api
guard:
authenticators:
- App\Security\TokenAuthenticator
logout:
path: api_logout
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
任何人都可以幫助我,我錯過了什么?
uj5u.com熱心網友回復:
您可以通過使用引數security.yaml宣告您的路由來限制對檔案中路由的訪問。access_controlIS_AUTHENTICATED_FULLY
例子:
access_control:
- { path: ^/authentication_token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/, roles: IS_AUTHENTICATED_FULLY }
- { path: ^/admin/, roles: ROLE_ADMIN }
- 路線
'/authentication_token':每個人都可以訪問 - Route
'/api/':只允許授權用戶訪問(角色無關緊要) - Route
'/admin/':僅允許具有 ROLE_ADMIN 角色的授權用戶訪問
注意:這在 symfony 官方檔案中有更詳細的描述。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/448585.html
