CSRF Implementation
To implement CSRF protection in a web application, you can follow these general steps:
Include a CSRF token in each form: When a user requests a page containing a form, the server generates a unique token and includes it in the form as a hidden field or as a cookie.
Verify the CSRF token on form submission: When the user submits the form, the server compares the token in the request with the token stored on the server. If they match, the request is considered valid and processed. If they don't match, the server rejects the request as a potential CSRF attack.
Here is an example implementation in Java using Spring Security:
- Configure Spring Security to use CSRF protection:
javaCopy code@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
- Include the CSRF token in each form:
htmlCopy code<form method="post" action="/example">
<input type="hidden" name="_csrf" value="${_csrf.token}">
<!-- Other form fields here -->
<button type="submit">Submit</button>
</form>
- Verify the CSRF token on form submission:
javaCopy code@PostMapping("/example")
public String handleFormSubmission(@RequestParam("_csrf") CsrfToken csrfToken, /* Other form parameters */) {
if (csrfToken != null && csrfToken.getToken().equals(request.getSession().getAttribute(CsrfToken.class.getName()))) {
// Process the form submission
} else {
// Invalid CSRF token, reject the request
}
}