如何使用 JWT 令牌验证路由?

How to authenticate route with JWT token?

我正在 symfony 中进行 JWT 令牌身份验证。登录后,我已经获得了一个有效期为5分钟的有效令牌。

我需要的是其他路线强制通行证Bearer TOKEN

我在 Postman 中试过,没有授权,它给了我结果。

如何让令牌成为路由的必需项。

这些是密码,我试过了。

TokenAuthenticator.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;
    }
}

security.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 }

任何人都可以帮助我,我缺少什么?

您可以通过在 access_control 中使用 IS_AUTHENTICATED_FULLY 参数声明您的路由来限制对 security.yaml 文件中路由的访问。

示例:

access_control: 
    - { path: ^/authentication_token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/, roles: IS_AUTHENTICATED_FULLY } 
    - { path: ^/admin/, roles: ROLE_ADMIN }

  1. 路由'/authentication_token':允许所有人访问
  2. 路由'/api/':只允许授权用户访问(角色无关紧要)
  3. 路由 '/admin/' : 只允许具有 ROLE_ADMIN 角色的授权用户访问

注意:这在官方symfony中有更详细的描述documentation