You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

验证步骤

  1. 打开浏览器开发者工具的Network面板,检查请求头是否包含Cookie: PHPSESSID=xxx
  2. 首次请求的响应头中确认存在Set-Cookie: PHPSESSID=xxx; ...
  3. 调试onAuthenticationFailure中的$session->all(),确认会话数据能正常存储和读取

内容的提问来源于stack exchange,提问作者RainMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:00:58