\Framework\MiddlewareCsrfTokenGenerateMiddleware

CSRF Token 生成 / 同步中间件(SPA 友好版)

设计说明(非常重要):

  1. CSRF Token 是「会话级别」的安全标识,而不是一次性验证码

  2. 在 SPA 场景下,Token 必须在 Session 生命周期内保持稳定

  3. 本中间件【只负责】:

    • 在 Session 中生成 Token(若不存在)
    • 将 Token 同步到 Cookie(XSRF-TOKEN)
  4. 本中间件【不负责】:

    • 校验 CSRF(应由独立的 Verify 中间件完成)
    • 每次请求刷新 Token(禁止!会导致并发请求失败)

前后端 CSRF 工作流:

请求前:

  • 后端生成 CSRF Token(仅首次)
  • 写入 Cookie:XSRF-TOKEN(非 HttpOnly)
  • Axios 从 Cookie 读取,并写入 Header:X-CSRF-TOKEN

请求中:

  • 后端校验 Header 中的 X-CSRF-TOKEN
  • 与 Session 中的 csrf_token 比对

失效时:

  • 返回 419(或 403)
  • 前端可选择重新拉取 Token 或引导重新登录

Summary

Methods
Properties
Constants
__construct()
handle()
No public properties found
No constants found
No protected methods found
No protected properties found
N/A
No private methods found
$tokenManager
$cookieName
$tokenId
N/A

Properties

$tokenManager

$tokenManager : \Framework\Security\CsrfTokenManager

Type

CsrfTokenManager

$cookieName

$cookieName : string

Type

string

$tokenId

$tokenId : string

Type

string

Methods

__construct()

__construct(\Framework\Security\CsrfTokenManager  $tokenManager, string  $cookieName = 'XSRF-TOKEN', string  $tokenId = 'default') : mixed

Parameters

\Framework\Security\CsrfTokenManager $tokenManager
string $cookieName
string $tokenId

Returns

mixed —

handle()

handle(\Symfony\Component\HttpFoundation\Request  $request, callable  $next) : \Symfony\Component\HttpFoundation\Response

Parameters

\Symfony\Component\HttpFoundation\Request $request
callable $next

Returns

\Symfony\Component\HttpFoundation\Response —