Symfony Workflow事件中获取当前用户返回null问题求助
解决Symfony Workflow Guard事件中Security::getUser()返回null的问题
先修正明显的代码错误
你代码里的事件订阅方法名不匹配:getSubscribedEvents中绑定的是onSomeEvent,但实际定义的方法是onCancellationRequest,这会导致事件触发时无法正确调用目标方法(如果是粘贴笔误,先修正为一致):
public static function getSubscribedEvents(): array { return [ 'workflow.rent_status.guard' => 'onCancellationRequest', ]; }
常见原因及解决方案
1. 事件触发环境是CLI命令行
CLI环境默认没有登录用户,Security上下文为空,所以getUser()返回null。
- 解决方案:如果需要在CLI中触发工作流,手动构建Security上下文:
// 在执行工作流转换的CLI命令中 use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use App\Repository\UserRepository; // 假设通过命令参数传入用户ID $userId = $input->getArgument('user-id'); $user = $this->userRepository->find($userId); // 创建令牌并注入到TokenStorage $token = new UsernamePasswordToken( $user, null, 'your_firewall_name', // 替换为你项目中的防火墙名称,比如main $user->getRoles() ); $this->tokenStorage->setToken($token);
2. 事件触发时Security上下文未初始化
如果工作流转换是在HTTP请求的早期阶段触发,或者在无请求的环境(如异步任务)中执行,Security上下文可能尚未构建。
- 解决方案:
- 对于HTTP请求:注入
RequestStack检查当前请求是否存在,确保请求已通过Security防火墙:use Symfony\Component\HttpFoundation\RequestStack; public function __construct( private Security $security, private RequestStack $requestStack, ) { } public function onCancellationRequest(Event $event) { $request = $this->requestStack->getCurrentRequest(); if (!$request) { throw new \RuntimeException('当前无有效HTTP请求,无法获取用户'); } $user = $this->security->getUser(); if (!$user) { throw new \RuntimeException('用户未登录'); } // 后续逻辑 } - 对于异步任务(如Messenger):在消息中携带用户ID,消费消息时获取用户并重建Security上下文,方法同CLI场景。
- 对于HTTP请求:注入
3. 用户未通过认证
确保触发工作流转换的请求中,用户已经登录且通过了Security防火墙的认证。可以在控制器中先检查$security->getUser()是否有效,再执行工作流转换。
内容的提问来源于stack exchange,提问作者sensorario
相关产品推荐
相关产品推荐

