【问题标题】:I get an invalid token?我得到一个无效的令牌?
【发布时间】:2021-08-14 09:48:55
【问题描述】:

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

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

获取 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);

【问题讨论】:

  • 您尝试过什么解决问题的方法?几天前看到了类似的问题,我可以建议启动 XDebug 来逐步执行代码 - 它的结构非常好:)
  • 我找不到问题:(
  • 你的环境变量正确吗?您似乎在两个地方添加了kernel.project_dir(尽管您显示的变量名称不同)。
  • 那么,您尝试过什么来解决这个问题?启动调试器了吗?
  • 我修改了 .env,我什至尝试使用硬值。我用调试器看不到任何东西

标签: symfony jwt


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2012-08-09
    • 2021-06-18
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多