CSRF Protection
What is CSER
The following is a sequence diagram and detailed explanation based on the CSRF attack process, combined with the attack process in multiple technical documents:
CSRF attack sequence diagram
User Browser Trusted Website A Malicious Website B Normal operation stage Visit Website A and log in Send login request Return to the cookie with successful login Store cookies (keep the session) Attack triggering stage Visit malicious Website B (such as clicking on the link) Request page Return to a page containing malicious code (such as JS that automatically submits the form) Forged request execution stage Automatically carry cookies to send malicious requests (such as transfers) Verify that the cookie is legal and executes the request User does not sense that the operation has been tampered with User Browser Trusted Website A Malicious Website B
Step-by-step interpretation of the attack process
User login to trusted website A
- The user logs into website A (such as a bank website) normally through the browser, and the server generates a session cookie and returns it to the browser.
- Key point: The browser will store this cookie, and all subsequent requests to website A will automatically carry this cookie (such as
Set-Cookie: session_id=abc123
)。
Users visit malicious website B
- The attacker induces users to visit malicious website B through phishing links, inducing advertisements, etc.
- Attack code example (from webpage 3):
<!-- Malicious websiteBPage --> <img src="http://Website A/Transfer?to=Attacker&amount=1000"><!-- Or byJSAutomatically submit form --> <script> ('<form action="http://Website A/Change password" method="POST">'); ('<input type="hidden" name="new_password" value="hacker123">'); ('</form>'); [0].submit(); </script>
The browser automatically sends forgery requests
- The code of malicious website B will trigger the browser to send a request to website A (such as transferring money or modifying passwords), and the browser will automatically carry the user's logged in cookies.
- Server Perspective: After Website A receives the request, it verifies that the cookie is legal, and mistakenly believes that it is the user's active operation and performs a malicious request.
Attack completed
- The user does not sense any exceptions (such as no page jump), but sensitive operations have been performed (such as fund transfer, password reset).
Key conditions for successful attack
- User logged into the trusted website A: Attacking active sessions that depend on users.
- CSRF protection is not enabled on Site A: If Token, Referer or secondary verification is not verified.
- Request parameters are predictable: for example, perform sensitive operations via GET requests (e.g.
GET / Transfer?to=Attender
)。
Defense measures (cited from web page 5, web page 6)
- Token verification: Embed a random token in the form or request header, and the server side verifies the legitimacy of the token.
- SameSite Cookie: Set the cookie
SameSite=Strict/Lax
Attributes that restrict cross-domain requests to carry cookies. - Referer Check: Verify that the request source is a trusted domain name.
From the sequence diagram, it can be seen that the core logic of CSRF attacks is to abuse the browser's cookie automatic portability mechanism, and the key to defense lies in blocking the attacker's ability to forge requests.
Introduction to CSRF for Security
According to Spring Security's official design philosophy and community practices (combining multiple technical documents and blogs), the core logic of its CSRF protection mechanism is as follows:
1. Spring Security's CSRF protection mechanism
Protection enabled by default
Automatic interception: Spring Security enables CSRF protection by default from version 4.0, throughCsrfFilter
Intercept requests from all non-secure HTTP methods (such as POST, PUT, DELETE).
Token verification process:
- Generate token: When the user first visits, the server generates a unique
CSRF Token
and stored inHttpSession
orCookie
(Use by defaultHttpSessionCsrfTokenRepository
)。 - Client carries token: This token must be included in a form or AJAX request (for example by hiding fields or request headers).
- Server verification: When the request arrives,
CsrfFilter
The token submitted by the client and the token stored on the server will be compared. If it is inconsistent, the request will be rejected (return 403 error).
Core Components
-
CsrfToken
Interface: defines the generation rules of the token, includingtoken
Value, parameter name (_csrf
) and request header name (X-CSRF-TOKEN
)。 -
CsrfTokenRepository
: -
HttpSessionCsrfTokenRepository
(Default): Token is stored in Session. -
CookieCsrfTokenRepository
: Tokens are stored in cookies and are suitable for front-end and back-end separation scenarios.
Configuration example:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .csrfTokenRepository(()); } }
Front-end integration method
Form page: Automatically inject tokens through template engines (such as Thymeleaf):
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
AJAX Request: Get the token from the cookie or Meta tag and add it to the request header:
// Get the token from the cookie (CookieCsrfTokenRepository is required)const token = (/XSRF-TOKEN=([^;]+)/)[1]; fetch('/api/data', { method: 'POST', headers: { 'X-XSRF-TOKEN': token } });
Extended protection strategy
- SameSite Cookie Attribute: Set the Cookie
SameSite=Strict/Lax
, restrict cross-domain requests to carry cookies (requires browser support). - Secondary verification: Overlay verification code or password confirmation for sensitive operations (such as transfers).
2. Hazard scenarios where CSRF protection is not enabled
If CSRF protection is not enabled, an attacker can use the following vulnerabilities to launch an attack:
Forged user operations:
- Automatically trigger malicious requests: embed through malicious pages
<img>
Or automatically submit the form to induce logged in users to trigger transfers, password modification and other operations. - Sample attack code:
<img src="/transfer?to=attacker&amount=10000">
Data tampering and leakage:
- Account information leakage: The attacker tampers with the user's email or mobile phone number, and can take over the account through the "Forgot Password" function in the future.
- Business logic bypass: for example, automatically following strange accounts, deleting user data, etc.
Enterprise-level risk:
- Supply Chain Attack: Infiltrates backdoors through CSRF vulnerabilities in administrator accounts, resulting in the penetration of enterprise systems.
- Compliance risk: Faces high fines for data breach of GDPR and other regulations.
3. Supplementary instructions of official documents
Although not directly quotedOfficial website, but the above mechanism is consistent with the official documents (can be verified through Spring Security official documents):
- Protection principle: Token-based synchronizer mode (Synchronizer Token Pattern).
- Disable scenarios: Only recommended for pure API services (no browser interaction)
().disable()
Turn off the protection.
Summarize
Spring Security effectively defends against cross-site request forgery attacks through the generation and verification mechanism of CSRF Tokens. If protection is not enabled, an attacker can use the user's logged in session to hijack sensitive operations, resulting in serious consequences such as data leakage and fund losses. Developers should choose the token storage method (Session/Cookie) based on business scenarios and ensure that the front-end correctly integrates the token.
Required parameters for CSRF prevention
The following is a summary table of standard CSRF protection parameters and their generation, use and failure rules, combining multiple technical documents and practical cases:
Parameter name | Generator | Generation time | Time to use | Failure conditions |
---|---|---|---|---|
CSRF Token | Server side | Generated when a user first visits a protected page | Carry when submitting a form or initiating a status change request (such as POST/PUT/DELETE). | Session expires, failure after a single use (single validity), time window exceeds (such as 5-10 minutes) |
SameSite Cookie | Server side | Generate when the user logs in for the first time | Automatically managed by the browser to restrict cross-domain requests to carry cookies | Cookie expires and expires, browser is closed (according to SameSite policy) |
Secondary verification parameters | Server or third-party system | Generate when the user triggers sensitive operations (such as transfers) | Secondary verification is required before performing key operations (such as SMS verification code) | The verification code expires after use and the timeout expires (such as 5 minutes) |
Detailed description
CSRF Token
- Generator: Server side pass
CsrfTokenRepository
Generate, e.g.HttpSessionCsrfTokenRepository
(Stored in a session) orCookieCsrfTokenRepository
(Stored in cookies). - Generation time: When a user first visits a page that requires CSRF protection (such as login pages, form pages), or dynamically generates a new token every time the page loads.
- Time to use: Must be embedded in requests for all non-secure methods (POST/PUT/DELETE), for example:
- Form: By hidden fields
<input type="hidden" name="_csrf" value="token">
。 - AJAX: Pass the request header
X-CSRF-TOKEN
orX-XSRF-TOKEN
transfer.
Failure conditions:
- Session expires: If the user session terminates, the token will be invalid.
- Single-time validity: Some system designs tokens are only available for single use (such as payment scenarios).
- Time window: Set the validity period of the token (such as 10 minutes), and the timeout will automatically expire.
SameSite Cookie
Generator: The server generates a session cookie when the user logs in and sets itSameSite
property.
Rules of use:
-
SameSite=Strict
: Prohibit cross-domain requests to carry cookies (for highly sensitive operations). -
SameSite=Lax
: Allow secure cross-domain requests (such as GET requests for navigation links). - Invalidation conditions: Follow the expired policy of cookies (such as the session cookie expires after the browser is closed).
Secondary verification parameters
- Generator: The server generates (such as SMS verification codes, dynamic passwords) when the user triggers sensitive operations.
- Time to use: Users need to confirm twice before key operations (such as password modification, large-scale transfer).
- Failure conditions: The verification code is invalid immediately after use, or is designed to be valid for a short period of time (such as 5 minutes).
Quote Source
- CSRF Token generation and verification logic:
- SameSite Cookie Mechanism:
- Secondary verification parameter design:
Through the above parameter combination (such as Token+SameSite+secondary verification), a multi-layer defense system can be built to effectively block CSRF attacks.
How Security is prevented
Spring Security avoids CSRF attacks through a combination of CSRF Token verification mechanism and defense policies. The following are its core implementation logic and key steps:
1. CSRF Token verification mechanism
Generate and store Token
- Token generation: Spring Security automatically generates a unique random CSRF token when the user first accesses a protected page.
- Used by default
HttpSessionCsrfTokenRepository
, store the token in the user session (HttpSession). - If it is a front-end and back-end separation architecture, it can be used
CookieCsrfTokenRepository
Store the token in a cookie and allow the front-end to read through JavaScript. - Token structure: contains three core attributes:
token
(Random value),parameterName
(parameter name, default_csrf
)、headerName
(Request header name, default isX-CSRF-TOKEN
)。
Client carries Token
- Form Submission:
Embed the token by hidden fields in the HTML form. For example, use the Thymeleaf template engine to automatically inject:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
- AJAX Request:
Pass the token through the request header. The front-end needs to get the token from the cookie or meta tag and add it to the request header:
// Get the token from the cookie (CookieCsrfTokenRepository is required)const token = (/XSRF-TOKEN=([^;]+)/)[1]; fetch('/api/data', { method: 'POST', headers: { 'X-XSRF-TOKEN': token } });
Server Verification Token
- Intercept and verification:
-
CsrfFilter
It will intercept all non-secure HTTP methods (such as POST, PUT, DELETE), extract the token from the request, and compare it with the token stored on the server. - If the token matches, the request passes.
- If the token is missing or does not match, a 403 Forbidden error is returned.
2. Defensive strategy expansion
SameSite Cookie Attributes
By setting cookiesSameSite
Attribute restricts cross-domain requests to carry cookies:
-
SameSite=Strict
: Only cookies are allowed to be carried on the same site. -
SameSite=Lax
: Allows some secure cross-site requests (such as navigation links).
Configuration example:
@Bean public CsrfTokenRepository csrfTokenRepository() { CookieCsrfTokenRepository repository = new CookieCsrfTokenRepository(); ("Lax"); return repository; }
Double Submit Cookie
- The server stores the token in both the cookie and form/request headers, and the two must be consistent during verification.
- Suitable for distributed systems, avoiding dependence on session storage.
Security method limitations
- By default, CSRF verification is only enabled for state modification classes such as POST, PUT, DELETE, PATCH, etc., while security methods such as GET, HEAD, OPTIONS do not require verification.
3. Configuration and best practices
Enable and Disable
Enabled by default: Spring Security 4.0+ CSRF protection is enabled by default.
- Manually close (not recommended):
().disable();
Front and back end separation configuration
- Backend configuration cookie storage Token:
().csrfTokenRepository(());
The front-end reads the token from the cookie and adds it to the request header.
Best Practices
- Always enable CSRF protection: unless the service is pure API and no browser interaction.
- Combined with HTTPS: Prevent Tokens from being stolen by middlemen.
- Periodic update of dependencies: Fix known vulnerabilities.
Summarize
Spring Security effectively blocks the attacker's ability to forge requests through the generation, delivery and verification mechanism of CSRF Tokens, combined with strategies such as SameSite Cookies and two-factor verification. Its design takes into account flexibility and security. Developers need to choose the appropriate token storage method based on the architecture (such as traditional MVC or front-end separation) and follow best practices to ensure full protection.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.