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
VerifyCsrfTokenmiddleware (enabled by default inapp/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 theXSRF-TOKENcookie) - As a request header
X-XSRF-TOKEN(Laravel automatically decodes theXSRF-TOKENcookie value for this header)
- As a request parameter named
GET,HEAD, andOPTIONSrequests are automatically exempt from CSRF checks (since they shouldn’t alter application state). You can add additional exceptions by editing the$exceptarray in theVerifyCsrfTokenmiddleware.
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 usingIlluminate\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-TOKENwith 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:
- Open your
config/session.phpfile. - Modify the
lifetimevalue (measured in minutes). For example, to set it to 1 hour:'lifetime' => 60, - If you’re using the
filesession driver, you can also toggle theexpire_on_closeoption totrueif 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

