Example to Implement CSRF Protection in Spring Security
We can implement the CSRF Token generation from the server side and it can be embedded into the client-side form to validate the CSRF tokens can access the server. In Implementation, we can prevent the authenticated attackers from the unknown domains.
CSRF Token Generation:
Java
// Security filter chain configuration for HTTP security public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // Configure CSRF token repository http.csrf() .csrfTokenRepository(csrfTokenRepository()) .and() .authorizeRequests() // Permit all requests to /public/**, /signup, and /login without authentication .requestMatchers( "/public/**" , "/signup" , "/login" ).permitAll() // Require authentication for any other requests .anyRequest().authenticated() .and() .formLogin() // Specify the login page and permit all access to it .loginPage( "/login" ).permitAll() // Configure the success handler for successful logins .successHandler(successHandler()) .and() .logout() // Specify the logout request matcher and permit all access to it .logoutRequestMatcher( new AntPathRequestMatcher( "/logout" )).permitAll() // Specify the logout success handler .logoutSuccessHandler( new HttpStatusReturningLogoutSuccessHandler()); // Build and return the security filter chain return http.build(); } // Configure the CSRF token repository private CsrfTokenRepository csrfTokenRepository() { // Create a new HttpSessionCsrfTokenRepository HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); // Set the session attribute name for the CSRF token repository.setSessionAttributeName( "_csrf" ); // Return the repository return repository; } |
Embedded with Client-side forms:
HTML
< form th:action = "@{/login}" method = "post" > < h2 >Login</ h2 > < input type = "hidden" th:name = "${_csrf.parameterName}" th:value = "${_csrf.token}" /> < div > < label for = "username" >Username:</ label > < input type = "text" id = "username" name = "username" required autofocus/> </ div > < div > < label for = "password" >Password:</ label > < input type = "password" id = "password" name = "password" required/> </ div > < button type = "submit" >Login</ button > </ form > |
Now, we can implement the simple user login management system that can be added the CSRF protection into the application.
CSRF Protection in Spring Security
In Spring Security, CSRF stands for Cross-Site Request Forgery. It is used to protect in the Spring Security mechanism. It is designed to prevent the attackers from executing unauthorized actions on behalf of the authenticated users.
Key Terminologies:
- CSRF Attack
- CSRF Token
- CSRF Token Repository
- CSRF Token Generation
- CSRF Token Validation