Jon Abraham
Jon Abraham

Reputation: 975

Disabling csrf gives 404 for Spring boot 2.0

I am using spring boot 2.1.4.RELEASE and trying to figure out 401 Unauthorized error.

Below is my webconfig class

public void configure(WebSecurity web) throws Exception {

            web.ignoring().antMatchers("/somepath/")

    }

@Override
    protected void configure(HttpSecurity http) throws Exception {
    if(securityEnabled) {
        http
                .csrf().disable()  
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .antMatchers("/somepath/").permitAll()
                .and()
                .httpBasic()
                .and()
                .anonymous().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
    }

In my main class i have excluded -

 @EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class,org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
    org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class})

Now when i try to test my api using http://localhost:8080/somepath then i am getting 401 unauthorized. But when i try the same endpoint with token then it works which means that authentication has not been disabled successfully. I would appreciate any help here.

Upvotes: 0

Views: 1292

Answers (1)

Bhushan Karia
Bhushan Karia

Reputation: 9

  1. Change the order of below statements.
  2. In the first statement, you are asking to have authentication for any request(all request)
  3. Then you are filtering requests with pattern("/somepath/") which is not relevant as the first statement satisfied.

        .anyRequest().authenticated()
        .antMatchers("/somepath/").permitAll()
    
  4. Remove below statement. When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

            .anonymous().disable()
    

So use below configure function with rearranged order that should solve this problem.

public void configure(WebSecurity web) throws Exception {

            web.ignoring().antMatchers("/somepath/")

    }

@Override
    protected void configure(HttpSecurity http) throws Exception {
    if(securityEnabled) {
        http
                .csrf().disable()  
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/somepath/").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic()


                .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
    }

Upvotes: 1

Related Questions