Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 730
user3687431 Avatar asked Jun 03 '26 00:06

user3687431


1 Answers

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

like image 109
Kyle Anderson Avatar answered Jun 06 '26 03:06

Kyle Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!