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

主宰稳场 提交于 2019-11-29 09:17:53

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!