#
Secure a Web Application for Cross Site Request Forgery (CSRF)
This tutorial explains to you how you can secure a Web Application with Spring 5 Security for Cross Site Request Forgery (CSRF).
Cross-Site Request Forgery (CSRF, XSRF or Sea surf) is an attack that forces an end user to execute unwanted
actions on a web application in which they're currently authenticated. In order to avoid such a problem,
Spring Security 5 use a token to tell the server that a particular request comes from the real / valid
application and not from outside the application. This is a default behavior.
In the article SPRING SECURITY: Secure Web Application
I have used .csrf().disable();
into the WebSecurityConfig class in order to disable this.
When CSRF is disabled into the Web Spring Application, the calls from the forms are simpler because you
don't have to add <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
in each form.
For instance the login page became:
In this case, WebSecurityConfig.java became something like this:
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String encoded = passwordEncoder.encode("pass1");
System.out.println("encoded="+encoded);
auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("user").password("u").authorities("USER")
.and()
.withUser("admin").password("a").authorities("USER","ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/myLogout").permitAll()
.antMatchers("/shared/**").permitAll()
.antMatchers("/no-access/*").denyAll()
.antMatchers("/secured/**").hasAuthority("USER")
.antMatchers("/admin-content/**").hasAuthority("ADMIN")
.and()
.formLogin() //Default login
.and()
.logout().logoutSuccessUrl("/myLogout").permitAll();
}
}