java - Spring Security OAuth 类型安全 SpEL 构建器

标签 java spring spring-security spring-security-oauth2

我们正在使用 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();
}

虽然这很好用,但我不喜欢:

  1. SpEL 标记本身可能会变得棘手,并且直到运行时才能验证
  2. 在多个 SpEL 字符串中重复常量(范围、角色)...
  3. 或者为了防止常量重复,150个字符长的连接可读性较差

一般来说,对于 spring-security,安全配置基类(WebSecurityConfigurerAdapterResourceServerConfigurerAdapter)提供的 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/

相关文章:

java - 如何避免 Buffer Reader 中的 NullPointErexception?

java - 使用 gson 将 json 对象列表转换为 java 对象,得到 null

java - Apache Ignite 支持万级缓存吗?

java - 使用 Boxlayout 导致我的面板只有父面板大小的一半

Spring security oauth2 和表单登录配置

spring-boot - 如何使用 Spring Boot 2.0.0.M4+ 在某些环境中要求 SSL

java - FileNotFoundException : class path resource ***/GlobalAuthenticationConfigurerAdapter. 类] 无法打开,因为它不存在

spring - 如何排除 gradle 依赖项

facebook - Spring Social facebook + Spring Security

java - 引用 spring bean 中的一组属性