【问题标题】:Spring Boot Security PermitAll with RequestHeaderMatcher not working带有 RequestHeaderMatcher 的 Spring Boot Security PermitAll 不起作用
【发布时间】:2020-10-02 09:12:26
【问题描述】:

在学习了关于 Maven Spring Boot 中的微服务和 OAuth2 的教程之后,我遇到了一个问题。我想从身份验证中排除请求,因此可以获得未经授权的数据。这只似乎不适用于我这样做的方式。有人可以帮我解决这个问题吗?

我遵循的教程:https://developer.okta.com/blog/2018/02/13/secure-spring-microservices-with-oauth#microservices-architectures-with-spring-boot--spring-cloud

我尝试了什么:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
                .authorizeRequests()
                .antMatchers("/**").authenticated()
                .and()
                .authorizeRequests()
                .andMatchers(HttpMethod.GET, "/beers").permitAll();
    }
}

当我尝试执行请求时,我必须进行身份验证。我该如何解决?

spring-security-oauth2-autoconfigure: 2.1.1.RELEASE

【问题讨论】:

    标签: java spring-boot spring-security oauth


    【解决方案1】:

    首先,您的配置与以下相同。只需删除那些不必要的重复 authorizeRequests()and() ,使其看起来更清晰:

      http.requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
                    .authorizeRequests()
                    .antMatchers("/**").authenticated()
                    .andMatchers(HttpMethod.GET, "/beers").permitAll();
    

    这意味着 Spring Security 只会处理具有 Authorization 标头的请求。否则,该请求将被忽略,并且不会应用任何 Spring Security 内容。

    所以如果请求有Authorization头,那么它就会开始按照声明的顺序从上到下检查规则(即authorizeRequests()配置的那些匹配器的东西)。一旦匹配了一个规则,底部规则将被忽略,不会被检查。

    由于您的第一条规则是匹配每个 HTTP 请求(“/**”),这使得它下面的所有规则永远不会执行并且没有任何意义。

    另一方面,如果你希望 spring security 完全忽略“/beers”,即使它的请求有Authorization 标头,你应该配置WebSecurity 忽略它:

     public void configure(WebSecurity web) throws Exception {
        web.ignoring()
           .antMatchers(HttpMethod.GET, "/beers");
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2018-02-14
      • 2018-01-31
      • 2017-08-20
      • 2021-03-06
      • 2019-02-17
      • 2019-09-27
      • 2018-04-17
      • 1970-01-01
      相关资源
      最近更新 更多