spring-bootcsrf-protection

Spring Boot CSRF


Tried to implement CSRF protection on the latest Spring Boot. All the examples on internet are based on user login and authentication, which I do not need.

My site does not have any sections requiring authentication. I would like

1) Rest requests come from within site. No direct request from outside with wget to be allowed.

2) All pages (routes) must be requested from the index page (/)

Included the security dependency in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

-- Defined users in application.properties (even though, I do not need)

-- App creates _csrf.token .

-- Created class extending WebSecurityConfigurerAdapter with "configure" method overriding.

Tried all suggested filters in "configure". It did not work and finally left it blank.

The problem is that Wget can get api pages directly. How to prevent it?


Solution

  • I've quickly put together a POC of this configuration:

    @Configuration
    @EnableWebSecurity
    @SpringBootApplication
    public class StackoverflowQ40929943Application extends WebSecurityConfigurerAdapter{
    
        public static void main(String[] args) {
            SpringApplication.run(StackoverflowQ40929943Application.class, args);
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/**").permitAll();
        }
    }
    

    The gist of it is Spring Boot + Security will secure all endpoints automatically. Here we explicitly allow requests to all endpoints. But, Spring Boot + Security automatically configures CSRF out of the box which we've left enabled. Thus you get the best of both worlds.

    NOTE: You'll probably need to refine this configuration further to meet your needs.

    Full Example on GitHub