我们正在使用 spring-security + spring-security-oauth 实现 OAuth2 资源服务器。
用例非常简单:
- A.某些资源仅供授权客户使用
- B.某些资源仅适用于(HTTP 基本)经过身份验证的用户
- C.所有其他资源仅适用于(HTTP 基本)经过身份验证的用户
通过 Java 配置,为了实现安全约束,我们使用了很多 SpEL,如下所示:
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// A. Only authorized clients
.antMatchers("/type-a").access("#oauth2.hasScope('READ_SOMETHING')")
// B. Both authorized clients and users
.antMatchers("/type-b").access("#oauth2.hasScope('READ_SOMETHING_ELSE') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
// ... (different flavors of B.) ...
// C. Everything else is for authenticated users
.anyRequest().hasRole("USER")
.and().httpBasic();
}
虽然这很好用,但我不喜欢:
- SpEL 标记本身可能会变得棘手,并且直到运行时才能验证
- 在多个 SpEL 字符串中重复常量(范围、角色)...
- 或者为了防止常量重复,150个字符长的连接可读性较差
一般来说,对于 spring-security,安全配置基类(WebSecurityConfigurerAdapter
、ResourceServerConfigurerAdapter
)提供的 HttpSecurity
构建器非常适合简单的约束,但复合/复杂约束最终会出现在 SpEL 中。
对于 spring-security-oauth2,我不知道除了 SpEL 之外还有什么其他方法。
问题:是否有现有的实用程序类为 OAuth2 SpEL 提供某种类型安全的流畅构建器?
类似于:
TypicalPerfectlyNamedSpringFrameworkDreamClass.builder()
.startExpressionGroup()
.hasOAuth2Scope("MY-SCOPE")
.endExpressionGroup()
.or()
.startExpressionGroup()
.isNotOAuth2Request()
.and()
.hasRole("ROLE_USER")
.endExpressionGroup()
.toString();
最佳答案
简短回答:“不,没有这样的实用程序”。
关于java - Spring Security OAuth 类型安全 SpEL 构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29517338/