I have a Spring Boot web application that uses Spring Security. The index.html page contains a method call (POST) to the controller that loads objects from MongoDB into a ArrayList and returns it so it can be displayed on the front page.
It seems like Spring Security is preventing POST requests for anonymous users. If I first login so the "/loadContent" method is called, and thereby log out, everything works well. I do pass the CSRF tokens before calling the method.
My "WebSecurityConfig":
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");
}
CSRF is enabled by default in spring security.
A possible solution is to disable it manually (see last line in code below).
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: