spring security permit仍然考虑在Authorization标头中传递令牌,如果令牌无效则返回401

use*_*529 15 authentication spring spring-security spring-security-oauth2

我在我的项目中使用spring security oauth.我通过在Spring安全性ResourceServerConfigurerAdapter中配置来从身份验证中排除一些URL.我补充道http.authorizeRequests().antMatchers(url).permitAll().

现在,我所看到的是,如果我没有将Authorization标头传递给这些网址,则不会对其进行身份验证.并且API被正确调用.

如果使用Authorization标头进行调用,则它会验证令牌并在未验证令牌时使调用失败.

我的问题是我需要做什么才能在我拥有permitAll的请求中忽略令牌.

Soo*_*Koh 7

Spring OAuth2将拦截所有带头的url:Authorization Bearer xxx.

避免Spring OAuth2拦截url.我创建了一个SecurityConfiguration,其顺序高于Spring OAuth2配置.

@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()
    }
}
Run Code Online (Sandbox Code Playgroud)

上述配置允许/ api/public/product/**和/ api/public/content/**由此配置处理,而不是由Spring OAuth2处理,因为此配置具有更高的@Order.

因此,即使将无效令牌设置为上述api调用也不会导致无效的访问令牌.