跳到内容

使令牌失效

编辑此页

令牌阻止列表依赖于 jti 声明,这是一个为跟踪和撤销 JWT 而设计的标准声明。 "jti" (JWT ID) 声明

阻止列表存储使用实现了 Psr\Cache\CacheItemPoolInterface 的缓存。 缓存将被阻止令牌的 jti 存储到缓存中,并且缓存项在令牌的 "exp" (过期时间) 声明之后过期

配置

要配置令牌阻止列表,请更新你的 `lexik_jwt_authentication.yaml` 文件

1
2
3
4
5
6
7
8
# config/packages/lexik_jwt_authentication.yaml
# ...
lexik_jwt_authentication:
# ...
    # invalidate the token on logout by storing it in the cache
    blocklist_token:
        enabled: true
        cache: cache.app

启用 blocklist_token

  • 通过作为参数传递给 `LexikBundleJWTAuthenticationBundleServicesJwtManager` 的 `LexikBundleJWTAuthenticationBundleServicesPayloadEnrichmentRandomJtiEnrichment`,向有效负载添加 jti 声明
  • 激活事件监听器 Lexik\Bundle\JWTAuthenticationBundle\BlockJWTListener,该监听器在注销时阻止 JWT (Symfony\Component\Security\Http\Event\LogoutEvent)

或由于用户未启用而在登录失败时阻止 JWT (Symfony\Component\Security\Core\Exception\DisabledException)

  • 激活事件监听器 Lexik\Bundle\JWTAuthenticationBundle\RejectBlockedTokenListener,该监听器在身份验证期间拒绝被阻止的令牌

要在注销时阻止 JWT,你必须在防火墙配置中激活注销或以编程方式执行

  • 通过防火墙配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # config/packages/security.yaml
    security:
        enable_authenticator_manager: true
        firewalls:
            api:
                ...
                jwt: ~
                logout:
                    path: app_logout
  • 在控制器操作中以编程方式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    use Symfony\Component\Security\Http\Event\LogoutEvent;
    //...
    class SecurityController
    {
        //...
        public function logout(Request $request, EventDispatcherInterface $eventDispatcher, TokenStorageInterface $tokenStorage)
        {
            $eventDispatcher->dispatch(new LogoutEvent($request, $tokenStorage->getToken()));
    
            return new JsonResponse();
        }
    ]

有关更多详细信息,请参阅 Symfony 注销

更改阻止列表存储

要更改阻止列表存储,请参阅 使用 FrameworkBundle 配置缓存

1
2
3
4
5
6
7
8
9
10
11
12
# config/packages/framework.yaml
framework:
    # ...
    cache:
        default_redis_provider: 'redis://127.0.0.1'
        pools:
            block_list_token_cache_pool:
                adapter: cache.adapter.redis
    # ...
    blocklist_token:
        enabled: true
        cache: block_list_token_cache_pool
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本