基于LDAP与JWT的安全架构中,如何全局覆盖LexikBundle成功处理器?
解决方案
要全局覆盖LexikJWTAuthenticationBundle的成功处理器,同时适配GesdinetJWTRefreshTokenBundle的刷新令牌逻辑,按以下步骤操作:
1. 自定义Lexik认证成功处理器
创建继承原处理器的自定义类,重写onAuthenticationSuccess方法实现自定义逻辑:
<?php namespace App\Security\Handler; use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler as BaseHandler; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class AuthenticationSuccessHandler extends BaseHandler { public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response { // 调用父类生成基础JWT响应 $response = parent::onAuthenticationSuccess($request, $token); // 自定义逻辑:添加额外字段到响应JSON $payload = json_decode($response->getContent(), true); $payload['custom_data'] = 'your_custom_value'; $response->setContent(json_encode($payload)); return $response; } }
2. 覆盖Lexik默认服务
在config/services.yaml中,通过Bundle的服务ID替换默认处理器(而非直接使用类的完全限定名):
services: lexik_jwt_authentication.handler.authentication_success: class: App\Security\Handler\AuthenticationSuccessHandler arguments: - '@lexik_jwt_authentication.jwt_manager' - '@lexik_jwt_authentication.parameter_bag' - '@event_dispatcher'
3. 自定义Gesdinet刷新令牌成功处理器
创建自定义类处理刷新令牌的成功逻辑:
<?php namespace App\Security\Handler; use Gesdinet\JWTRefreshTokenBundle\Security\Http\Authentication\AuthenticationSuccessHandler as BaseRefreshHandler; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class RefreshTokenSuccessHandler extends BaseRefreshHandler { public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response { $response = parent::onAuthenticationSuccess($request, $token); // 自定义刷新响应逻辑 $payload = json_decode($response->getContent(), true); $payload['refresh_metadata'] = 'custom_refresh_info'; $response->setContent(json_encode($payload)); return $response; } }
4. 覆盖Gesdinet默认服务
在services.yaml中替换刷新令牌的成功处理器服务:
services: # ... 上述Lexik服务配置 gesdinet_jwt_refresh_token.handler.authentication_success: class: App\Security\Handler\RefreshTokenSuccessHandler arguments: - '@gesdinet_jwt_refresh_token.jwt_manager' - '@gesdinet_jwt_refresh_token.refresh_token_manager' - '@gesdinet_jwt_refresh_token.parameter_bag' - '@event_dispatcher'
关键说明
你之前的配置未生效,是因为直接使用类的完全限定名作为服务ID,但LexikBundle实际注册的服务ID是lexik_jwt_authentication.handler.authentication_success。Symfony会优先加载Bundle预设的服务,只有通过覆盖这个服务ID的定义,才能替换默认处理器。
内容的提问来源于stack exchange,提问作者Cyril F
相关产品推荐
相关产品推荐

