Symfony 5.3.9手动登出用户后切换登录用户异常问题
问题:Symfony 5.3.9登出后旧用户信息仍保留在me接口中
我使用Symfony 5.3.9搭配Vue3开发,目标是实现点击按钮调用接口完成用户登出并切换登录用户。当前编写的登出接口(token方法)代码如下:
public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher, SessionInterface $session, Security $security) { $this->tokenStorage = $tokenStorage; $this->eventDispatcher = $eventDispatcher; $this->session = $session; $this->security = $security; } public function token(Request $request): JsonResponse { $this->tokenStorage->setToken(null); $this->session->invalidate(); $this->get('security.token_storage')->setToken(null); $user = $this->getUser(); // 此处返回或var_dump查看user,结果为null,符合预期 }
在该登出接口中,登出后$user返回null,这部分表现正常;但调用另一个me接口时,旧用户信息依然存在,me接口代码如下:
public function me(UserInterface $user = null): JsonResponse { $username = $user->getUsername(); return new JsonResponse(['username' => $username]); }
此处$user本应为null却仍显示旧用户信息。我已尝试执行以下操作,但用户信息始终未被清除:
$this->tokenStorage->setToken(null); $this->session->invalidate(); $this->get('security.token_storage')->setToken(null);
解决建议
使用Symfony标准登出流程
不要手动操作tokenStorage和session,直接调用Security组件的logout方法,它会完整处理token清除、会话失效及相关事件触发:public function token(Request $request, Security $security): JsonResponse { $security->logout(false); // false表示不跳转,适合API场景 $user = $this->getUser(); // 此时应为null return new JsonResponse(['status' => 'logged_out']); }清理前端缓存的认证信息
前端Vue可能在localStorage或sessionStorage中存储了旧的认证token,登出接口返回后,前端要同步清除这些存储的信息,避免后续请求携带旧凭证。修改me接口的用户获取逻辑
避免依赖方法参数注入UserInterface,改为从TokenStorage手动获取用户,确保实时获取当前会话状态:public function me(TokenStorageInterface $tokenStorage): JsonResponse { $token = $tokenStorage->getToken(); $user = $token ? $token->getUser() : null; if (!$user instanceof UserInterface) { return new JsonResponse(['username' => null], 200); } return new JsonResponse(['username' => $user->getUsername()], 200); }清除"记住我"Cookie(若启用)
如果项目启用了"记住我"功能,需要额外清除对应的Cookie:public function token(Request $request, Security $security): JsonResponse { $security->logout(false); // 清除记住我Cookie,名称对应security.yaml中remember_me的name配置 $response = new JsonResponse(['status' => 'logged_out']); $response->headers->clearCookie('REMEMBERME'); return $response; }确保会话失效后的Cookie更新
session->invalidate()会生成新的Session ID,登出接口的响应需要正确携带新的Session Cookie,避免前端保留旧会话ID。
内容的提问来源于stack exchange,提问作者Oten
相关产品推荐
相关产品推荐

