【问题标题】:@EnableWebSecurity and #oauth2.clientHasRole - Why doesn't it work?@EnableWebSecurity 和 #oauth2.clientHasRole - 为什么它不起作用?
【发布时间】:2019-12-11 11:56:15
【问题描述】:

一段时间以来,我一直在为此绞尽脑汁。我有一个来自 Azure 的 client_credentials JWT 令牌,有效负载中包含以下内容:

"roles": [ "read", "write" ]

我的安全配置类似于:

@Configuration
@EnableWebSecurity
public SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests()
            .antMatchers(HttpMethod.GET, "/api", "/api/**").access("#oauth2.clientHasRole(\"read\")")
            .antMatchers(HttpMethod.POST, "/api", "/api/**").access("#oauth2.clientHasRole(\"write\")")
            .anyRequest().access("#oauth2.isClient()");
    }
}

我正在使用:

org.springframework.boot:spring-boot-starter-oauth2-resource-server:2.1.0.RELEASE

我们使用了一个使用 @EnableResourceServer 的私有库,但后来停止使用它,因为它需要通过创建自定义代码来连接到 Azure 的内部支持 - 而不是使用似乎开箱即用的 @EnableWebSecurity,除了获得这些特殊权限。

那么为什么#oauth2 安全表达式方法不起作用呢?我得到以下异常:

java.lang.IllegalArgumentException: Failed to evaluate expression '#oauth2.clientHasRole("read")'

我尝试过@EnableGlobalMethodSecurity(prePostEnabled = true) 并通过覆盖GlobalMethodSecurityConfiguration.createExpressionHandler() 手动返回OAuth2MethodSecurityExpressionHandler(),但这不起作用。请参阅此this answer 作为参考。

作为一种替代方法,我还尝试考虑添加一些新的GrantedAuthoritys,但在不亲自手动验证令牌的情况下弄清楚如何做到这一点没有运气。我看到使用了SecurityExpressionRoot,但是在检查hasRole()时,它依赖于设置的权限,它是空的。

所以我希望#oauth.clientHasRole() 功能能够正常工作。任何帮助将不胜感激!

【问题讨论】:

    标签: spring-boot azure-active-directory spring-security-oauth2


    【解决方案1】:

    我最终关注了这个spring document,并通过生成一个 bean 并引用它来制作我自己的安全表达式。我不喜欢这个答案,并且希望 #oauth2 表达式能够开箱即用。如果有人有首选答案,请发布。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2017-11-07
      • 2020-03-28
      • 2015-03-10
      • 2020-11-09
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多