CSRF is enabled by default in spring security.
A possible solution is to disable it manually (see last line in code below).
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/loadContent")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and().csrf().disable();
}
Update:
If you want to use csrf, which I encourage, maybe think about securing an additional REST endpoint e.g. starting with /api/.
In the example below these endpoints are secured using Basic Authorization with a user called api
, but you can easily change it to allow anonymous users to request to resources:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("api").password("api").roles("API").and()
.withUser("user").password("user").roles("USER").and()
.withUser("admin").password("admin").roles("USER", "API", "ADMIN");
}
@Configuration
@Order(1) // higher order = lower priority
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
// no csrf when communicating directly with the backend api
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasAnyRole("API")
.and()
.httpBasic()
.and()
.csrf().disable();
http.sessionManagement().disable();
}
}
@Configuration
@Order(2) // higher order = lower priority
public static class UIWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasAnyRole("USER", "ADMIN").anyRequest().authenticated();
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.httpBasic().disable();
}
}
}