Spring security allowAll still considers the token passed in the authorization header and returns 401 if the token is invalid

I am using spring security oauth in my project. I exclude some URLs from authentication by setting in spring security ResourceServerConfigurerAdapter. I have added http.authorizeRequests().antMatchers(url).permitAll().

Now, I see that if I do not pass the authorization header to these URLs, it will not be authenticated. And the API is called correctly.

If the call is made with an authorization header, it checks the token and does not make the call if the token is not verified.

My question is what do I need to make the token be ignored in the request, for which I have AllowAll.

+4
source share
1 answer

Spring OAuth2 will intercept the entire url with the header: xxx identity.

To avoid Spring OAuth2 from intercepting URLs. I created a SecurityConfiguration that has a higher order than Spring OAuth2 Configuration.

@Configuration
@EnableWebSecurity
@Order(1) // this is important to run this before Spring OAuth2 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<RequestMatcher> requestMatchers = new ArrayList<RequestMatcher>();
        // allow /api/public/product/** and /api/public/content/** not intercepted by Spring OAuth2
        requestMatchers.add(new AntPathRequestMatcher("/api/public/product/**"));
        requestMatchers.add(new AntPathRequestMatcher("/api/public/content/**"));

    http
        .requestMatcher(new OrRequestMatcher(requestMatchers))
    .authorizeRequests()
      .antMatchers("/api/public/product/**", "/api/public/content/**").permitAll()
    }
}

The above configuration allows us to handle this configuration / api / public / product / ** and / api / public / content / **, rather than Spring OAuth2, because this configuration has a higher @Order.

Therefore, even setting an invalid token for a call above api will not result in an invalid access token.

+3
source

All Articles