【问题标题】:Security on Spring resources only works with '@PreAuthorize'Spring 资源的安全性仅适用于“@PreAuthorize”
【发布时间】:2017-11-23 06:07:45
【问题描述】:

我不知道我做错了什么,但是当我尝试使用 ResourceServerConfigurerAdapter 保护一些 REST 资源时它不起作用。我只能使用@PreAuthorize 或在WebSecurityConfigurerAdapter 上设置安全性来实现我的目标。

实际上,WebSecurityConfigurerAdapter 正在窃取HttpSecurity 设置的所有可能性。我相信它与过滤顺序有关。我搜索了有关文档的信息,但发现它很模糊。我知道在 Spring Boot 版本 1.5+ 上,ResourceServerConfigurerAdapter 的过滤顺序已更改,我只有在属性上设置新顺序后才能使其工作:security.oauth2.resource.filter-order=3

更具体地说,这段代码(ResourceServerConfigurerAdapter)没有任何结果:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.requestMatcher(new OAuthRequestedMatcher())
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .antMatchers("/api/hello").access("hasAnyRole('USER')")
            .antMatchers("/api/me").hasAnyRole("USER", "ADMIN");
}

只能在控制器方法上保护"/api/hello""/api/me"注释@PreAuthorize

@PreAuthorize("hasAnyRole('USER','ADMIN')")
@GetMapping("/api/hello")
public ResponseEntity<?> hello() {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    String msg = String.format("Hello %s", name);
    return new ResponseEntity<Object>(msg, HttpStatus.OK);
}

它正在工作,但是,我担心它可以以更好的方式完成。有什么想法吗?

【问题讨论】:

    标签: spring spring-boot spring-security spring-security-oauth2


    【解决方案1】:

    经过一番挖掘,我找到了解决方案。问题确实与过滤顺序有关。 Pivotal 的人更改了 Oauth2 资源过滤器顺序,您可以在这段摘自 Spring Boot 1.5 发行说明的段落中看到:

    OAuth 2 资源过滤器

    OAuth2 资源过滤器的默认顺序已从 3 更改为 SecurityProperties.ACCESS_OVERRIDE_ORDER - 1. 这将它放在 执行器端点,但在基本身份验证过滤器链之前。 可以通过设置恢复默认 security.oauth2.resource.filter-order = 3

    但是,正如@ilovkatie 在此thread 上所指出的,WebSecurityConfigurerAdapter 的顺序也更改为 100,优先于 ResourceServerConfigurerAdapter

    因此,与其更改ResourceServerConfigurerAdapter 的属性顺序,更优雅的解决方案是在WebSecurityConfigurerAdapter 上使用@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)

    这将使资源配置优先于WebSecurityConfigurerAdapter,并且可以在ResourceServerConfigurerAdapter 上使用HttpSecurity 设置安全性,从而无需使用@PreAuthorize 注释。

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 2016-07-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 2020-07-06
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多