为什么我的jwt令牌永不过期?

为什么我的jwt令牌永不过期?

问题描述:

我继承使用该控制器来验证用户symfony项目:为什么我的jwt令牌永不过期?

class TokenController extends FOSRestController 
{ 
    public function postTokensAction(Request $request) 
    { 
     $username = $request->request->get('username'); 
     $password = $request->request->get('password'); 

     $user = $this->get('fos_user.user_manager') 
        ->findUserByUsername($username); 

     if (!$user) { 
      throw $this->createNotFoundException(); 
     } 

     $passwordEncoder = $this->get('security.password_encoder'); 
     if(!$passwordEncoder->isPasswordValid($user, $password)) { 
      throw $this->createAccessDeniedException(); 
     } 

     $groups = ['foo', 'bar']; 
     $context = SerializationContext::create() 
         ->setGroups($groups); 

     $token = $this->get('lexik_jwt_authentication.encoder') 
         ->encode(['username' => $user->getUsername()]); 

     $user = $this->get('jms_serializer') 
        ->toArray($user, $context); 

     return new JsonResponse([ 
      'token' => $token, 
      'user' => $user 
     ]); 
    } 
} 

而客户请求更新:登录后令牌本应到期时10秒。所以,按照文档,我添加了这个监听器。

<?php 

namespace AppBundle\EventListener; 

use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent; 

class JWTCreatedListener 
{ 
    public function onJWTCreated(JWTCreatedEvent $event) 
    { 
     $expiration = new \DateTime('now'); 
     $expiration->add(new \DateInterval('PT10S')); 
     $payload = $event->getData(); 
     $payload['exp'] = $expiration->getTimestamp(); 
     $event->setData($payload); 
    } 
} 

,当然,我已经打上听者如果我与邮差令牌来观察事件

acme_api.event.jwt_created_listener: 
    class: AppBundle\EventListener\JWTCreatedListener 
    tags: 
     - { name: kernel.event_listener, event: lexik_jwt_authentication.on_jwt_created, method: onJWTCreated } 

,并用它来作以下请求我可以为那些天要求和几天。令牌永不过期。我的JWTCreatedListener似乎不起作用。

怎么了?

+0

看起来像'lexik_jwt_authentication.on_jwt_created'事件在每个请求的每次触发或者是不永远不要说。你有没有解决这个问题https://*.com/questions/45617269/the-lexik-jwt-authentication-on-jwt-created-is-not-present-in-symfonys-profil? – yceruto

它们永不过期,因为您使用的是JWT编码器的低级api。正如你所看到的(因为你称之为),encode()需要有效载荷。 为了获得令牌到期,有效负载必须包含exp声明,并将过期时间戳记作为值。
这由lexik_jwt_authentication.jwt_manager服务处理,该服务使用lexik_jwt_authentication.encoder.token_ttl配置选项的值来确定到期日期。设置它并使用$this->get('lexik_jwt_authentication.jwt_manager')->create($user)创建令牌,然后使用$this->get('lexik_jwt_authentication.jwt_manager')->decode($token)解码/验证它。

注意,对于正常使用此包(允许挂接到它提供的所有事件),你应该考虑使用适当的安全配置(如在解说中所示),而不是在你的控制器通过手这样做。

的关键是在这里:

$token = $this->get('lexik_jwt_authentication.encoder') 
       ->encode(['username' => $user->getUsername()]); 

我需要添加另一个参数编码功能:

$token = $this->get('lexik_jwt_authentication.encoder') 
       ->encode([ 
        'username' => $user->getUsername(), 
        'exp'  => (new \DateTime('+30 minute'))->getTimestamp(), 
       ]);