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

后端 未结 2 651
说谎
说谎 2020-12-18 19:02

I am using spring security oauth in my project. I am excluding some urls from authentication by configuring in spring security ResourceServerConfigurerAdapter. I added

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 19:44

    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 requestMatchers = new ArrayList();
            // 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.

提交回复
热议问题