我得到一个无效的令牌?

时间:2021-05-26 07:02:13

标签: symfony jwt

我在一个 Docker 项目下工作。 Symfony 5.

  • 注册顺利,我已经在数据库中注册了用户
  • 连接顺利,我收到令牌
  • 在连接过程中,auth 表中有一条记录行带有令牌
  • 另一方面,对受保护路由的访问表明令牌无效

GET http://localhost:8003/api/users/13
授权承载 ...................................................... ....

{
    "code": 401,
    "message": "Invalid JWT Token"
}

security.yml

security:
  encoders:
    App\Entity\User:
      algorithm: bcrypt

  providers:
    app_user_provider:
      entity:
        class: App\Entity\User
        property: email

  firewalls:
    refresh:
      pattern: ^/api/token/refresh
      stateless: true
      anonymous: true

    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    doc:
      pattern: ^/doc
      security: false

    login:
      pattern: ^/api/login
      stateless: true
      anonymous: true
      json_login:
        username_path: email
        check_path: /api/login/token
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure

    user_register:
      pattern: ^/api/user/register
      stateless: true
      anonymous: true

    main:
      pattern: ^/api
      stateless: true
      anonymous: false
      provider: app_user_provider
      guard:
        authenticators:
          - lexik_jwt_authentication.jwt_token_authenticator

  access_control:
    - { path: ^/api/token/refresh, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/user/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/, roles: IS_AUTHENTICATED_FULLY }

lexik_jwt_authentication.yaml

lexik_jwt_authentication:
  private_key_path: "%kernel.project_dir%/%env(JWT_PRIVATE_KEY_PATH)%"
  public_key_path: "%kernel.project_dir%/%env(JWT_PUBLIC_KEY_PATH)%"
  pass_phrase: "%env(JWT_PASSPHRASE)%"

  token_ttl: 3600 # token TTL in seconds, defaults to 1 hour
  user_identity_field: email 
  clock_skew: 0

  encoder:
    service: lexik_jwt_authentication.encoder.lcobucci

    signature_algorithm: RS256

  token_extractors:
    authorization_header:
      enabled: true
      prefix: Bearer
      name: Authorization

    cookie:
      enabled: false
      name: BEARER

    query_parameter:
      enabled: false
      name: bearer

我使用正确的密码创建了 2 个证书:

.env

...
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=f8bfe4494b7cf3032d642a3e72dcac53

/config/jwt/private.pem
/config/jwt/public.pem

\vendor\Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator.php

public function getCredentials(Request $request)
    {
        $tokenExtractor = $this->getTokenExtractor();

        if (!$tokenExtractor instanceof TokenExtractorInterface) {
            throw new \RuntimeException(sprintf('Method "%s::getTokenExtractor()" must return an instance of "%s".', __CLASS__, TokenExtractorInterface::class));
        }

        if (false === ($jsonWebToken = $tokenExtractor->extract($request))) {
            return;
        }

        $preAuthToken = new PreAuthenticationJWTUserToken($jsonWebToken);

        try {
            dump($preAuthToken);                                // --------------
            dump($this->jwtManager->decode($preAuthToken));     //    ERROR HERE
                                                                // -------------- 
            if (!$payload = $this->jwtManager->decode($preAuthToken)) {
                throw new InvalidTokenException('Invalid JWT Token');
            }

            $preAuthToken->setPayload($payload);
        } catch (JWTDecodeFailureException $e) {
            if (JWTDecodeFailureException::EXPIRED_TOKEN === $e->getReason()) {
                $expiredTokenException = new ExpiredTokenException();
                $expiredTokenException->setToken($preAuthToken);
                throw $expiredTokenException;
            }
            throw new InvalidTokenException('Invalid JWT Token', 0, $e);
        }

        return $preAuthToken;
    }

转储($preAuthToken);

JWTTokenAuthenticator.php on line 106:
Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\PreAuthenticationJWTUserToken {#598
  -rawToken: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOjIyLCJ1c2VybmFtZSI6InRvdG8xMUB0b3RvLmZyIiwiaWF0IjoxNjIyMDI3NzQ4fQ.COr_fuXAH8iq3Ecr8mJVIVVdLI6H5zv7419gvQwLy6Q"
  -payload: null
  -credentials: null
  -guardProviderKey: null
  -user: null
  -roleNames: []
  -authenticated: false
  -attributes: []
}
  • 这是在请求中传递的正确令牌

此行出现错误:$this->jwtManager->decode($preAuthToken)
和触发器:new InvalidTokenException('Invalid JWT Token', 0, $e);

1 个答案:

答案 0 :(得分:0)

您使用的是哪个版本的 LexikJWTAuthentication ?我猜最新的 symfony 5,你应该使用参数 public_key 而不是 public_key_pathhttps://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/1-configuration-reference.md