我继承了一个 Symfony 项目,它使用这个控制器来验证用户:
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 }
如果我通过 Postman 获得令牌并使用它来发出以下请求,我可以在几天和几天内发出这些请求。令牌永不过期。我的 JWTCreatedListener 似乎不起作用。
怎么了?