Symfony会话连接尝试计数异常:Postman正常Fetch无法存储PHPSESSID
解决方案
1. 修复Fetch请求,携带会话凭证
Fetch API默认不会自动发送Cookie,导致后端每次收到的请求都是新会话。你需要在请求中添加凭证配置,确保PHPSESSID Cookie被传递到后端:
fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'xxx', password: 'xxx' }), credentials: 'include' // 关键:跨域场景用include,同域用same-origin })
2. 修正中间件中Session的获取时机
你在构造函数里提前调用了$requestStack->getSession(),此时请求的会话上下文还未完全初始化,后续操作自然拿不到正确的会话数据。应该在onAuthenticationFailure方法内动态获取当前请求的Session:
public function __construct(JWTEncoderInterface $jwtEncoder, RequestStack $requestStack, ManagerRegistry $doctrine) { $this->jwtEncoder = $jwtEncoder; $this->requestStack = $requestStack; $this->doctrine = $doctrine; // 移除构造函数中的$this->session赋值 } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse { // 动态获取当前请求的Session $session = $this->requestStack->getSession(); $this->loginResricted(); $this->incrementAttempt($session); // 将Session传入方法使用 return new JsonResponse(['error' => true, 'message' => 'Authentication failed'], 401); } // 调整incrementAttempt方法依赖Session参数 private function incrementAttempt(SessionInterface $session) { $attempts = $session->get('login_attempts', 0); $session->set('login_attempts', $attempts + 1); }
3. 检查Symfony会话Cookie的跨域配置(如果是跨域场景)
如果前端和后端不在同一域名下,需要修改Symfony的会话Cookie配置,允许跨域携带。编辑config/packages/framework.yaml:
framework: session: handler_id: null cookie_secure: auto cookie_samesite: lax # 跨域场景可设为none(需配合cookie_secure: true) cookie_path: / cookie_domain: '%env(APP_COOKIE_DOMAIN)%' # 填写前端域名,比如example.com
验证步骤
- 打开浏览器开发者工具的Network面板,检查请求头是否包含
Cookie: PHPSESSID=xxx - 首次请求的响应头中确认存在
Set-Cookie: PHPSESSID=xxx; ... - 调试
onAuthenticationFailure中的$session->all(),确认会话数据能正常存储和读取
内容的提问来源于stack exchange,提问作者RainMan
相关产品推荐
相关产品推荐

