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

Laravel CSRF Token技术问题:生成、位置、有效期及匹配规则

Hey there! Let's break down all your questions about Laravel's CSRF tokens one by one—this stuff is foundational for keeping your app safe from cross-site request forgery attacks, so it’s awesome you’re diving into the details.

1. CSRF Token 匹配规则

Laravel’s CSRF validation works by verifying that the token sent with a state-modifying request (non-GET/HEAD/OPTIONS) matches the token stored in the user’s active session. Here’s the exact breakdown:

  • The VerifyCsrfToken middleware (enabled by default in app/Http/Kernel.php) handles all validation logic.
  • You can pass the token to Laravel in three valid ways:
    • As a request parameter named _token (most common in HTML forms: <input type="hidden" name="_token" value="{{ csrf_token() }}">)
    • As a request header X-CSRF-TOKEN (ideal for AJAX calls—pull this value from the XSRF-TOKEN cookie)
    • As a request header X-XSRF-TOKEN (Laravel automatically decodes the XSRF-TOKEN cookie value for this header)
  • GET, HEAD, and OPTIONS requests are automatically exempt from CSRF checks (since they shouldn’t alter application state). You can add additional exceptions by editing the $except array in the VerifyCsrfToken middleware.

2. 如何生成 CSRF Token

Laravel generates the CSRF token on-demand when it’s first needed—like when you call the csrf_token() helper or use the @csrf Blade directive. Under the hood:

  • It calls the token() method on the user’s session instance. If no token exists in the session, Laravel generates a random 32-character string using Illuminate\Support\Str::random(32).
  • This newly generated token is then stored in the user’s session for all future validation checks.

3. 存储位置

The CSRF token lives in two key places:

  • Server-side: The authoritative copy is stored in the user’s session (the storage backend depends on your session driver—file, database, Redis, etc.—configured in config/session.php). This is what Laravel checks against during validation.
  • Client-side: Laravel sets a cookie named XSRF-TOKEN with the same token value. This cookie is not HTTP-only, so your frontend JavaScript can read it to set request headers for AJAX requests.

4. 有效期时长

By default, the CSRF token’s lifespan is directly tied to the user’s session duration. Laravel’s default session lifetime is 120 minutes (2 hours), set in config/session.php under the lifetime key. The token expires when the session expires—either after the idle timeout elapses or when the user logs out.

5. 为什么刷新页面后 Token 未变化

This is intentional behavior! The CSRF token is linked to the user’s active session, not individual page loads. As long as the session remains valid (the user hasn’t been idle longer than the session timeout, or logged out), Laravel will reuse the same token. This simplifies frontend code—forms and AJAX calls don’t need to fetch a new token every time the page refreshes.

6. 如何调整有效期

Since the CSRF token’s expiration is tied to the session, adjusting the session lifetime will automatically adjust the token’s validity:

  1. Open your config/session.php file.
  2. Modify the lifetime value (measured in minutes). For example, to set it to 1 hour:
    'lifetime' => 60,
    
  3. If you’re using the file session driver, you can also toggle the expire_on_close option to true if you want sessions (and thus CSRF tokens) to expire when the user closes their browser.

Note: It’s not recommended to decouple the CSRF token’s expiration from the session—doing so could lead to edge cases where the session is still active but the token is invalid, causing unnecessary validation failures.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:33:41