spring security permitAll still considering token passed in Authorization header and returns 401 if token is invalid spring security permitAll still considering token passed in Authorization header and returns 401 if token is invalid spring spring

spring security permitAll still considering token passed in Authorization header and returns 401 if token is invalid


Spring OAuth2 will intercept all url with header: Authorization Bearer xxx.

To avoid Spring OAuth2 from intercept the url. I have created a SecurityConfiguration which has 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 /api/public/product/** and /api/public/content/** to be handled by this configuration, not by Spring OAuth2 because this configuration has higher @Order.

Therefore, even setting invalid token to above api call will not result in invalid access token.


As per spring-oauth2 docs https://projects.spring.io/spring-security-oauth/docs/oauth2.html

Note: if your Authorization Server is also a Resource Server then there is another security filter chain with lower priority controlling the API resources. Fo those requests to be protected by access tokens you need their paths not to be matched by the ones in the main user-facing filter chain, so be sure to include a request matcher that picks out only non-API resources in the WebSecurityConfigurer above.

So define WebSecurityConfigurer implementation with higher order than ResourceServerConfig.