401 on request where `permitAll()` specified

Viewed 172

I have this WebSecurityConfigurerAdapter config:

@EnableWebSecurity
public class HttpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .authorizeRequests()

                .mvcMatchers("/auth/**").permitAll()

                .anyRequest().authenticated()

                .and()
                .oauth2ResourceServer().jwt()
        ;
    }
}

When I make a request to auth, I get a 401, until I pass some authorisation - which isn't appropriate for this endopint.

I would assume this has something to do with .anyRequest().authenticated(). I had read before that this shouldn't affect the permitAll()s - have I misconfigured something?

2 Answers

Your request is probably being rejected because you didn't provide a CSRF token. By default, Spring Security enables it for every POST request and you need to explicitly disable it.

@EnableWebSecurity
public class HttpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .mvcMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer().jwt();
    }
}

You can add the following property to your application.yml file so you can be able to see why your request is being rejected if CSRF is not the case:

logging:
  level:
    org.springframework.security: TRACE

If u are using jwt filter,it won't work even if you added permitAll() .if you remove the filter, it will work fine.

Related