user4274413
user4274413

Reputation:

Spring boot csrf filter

I was trying to enable csrf filter for some specific api calling and for the others no need of csrf filter.What I have done is

@Override

protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable().authorizeRequests().antMatchers("/public/**").permitAll();
    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
    http.csrf().disable().addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).authorizeRequests().antMatchers("/rest/**").permitAll();
}

The problem is when I was calling localhost:8080/public/hello

An error was showing

"message": "Missing or non-matching CSRF-token"

I am using Spring boot and Spring Security.

Thanks for any help.

Upvotes: 4

Views: 9270

Answers (2)

Soham
Soham

Reputation: 4417

http.antMatcher("/public/**").authorizeRequests().anyRequest().permitAll();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.antMatcher("/rest/**").addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).csrf().disable();

Or you can do like this.I think both will be working.

http.antMatcher("/public/**").csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.antMatcher("/rest/**").addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).csrf().disable();

Upvotes: 5

Josh Ghiloni
Josh Ghiloni

Reputation: 1300

Try changing http.csrf().disable() to http.antMatcher("/public/**").csrf().disable() and http.antMatcher("/rest/**").csrf().disable(). You will likely have to put those two lines each in their own WebSecurityConfigurerAdapter.

That will tell Spring-Security to create multiple HTTP Security Filter Chains (akin to having multiple <http/> blocks in the XML model).

Upvotes: 2

Related Questions