【问题标题】:Protect specific resources id with OAuth2 on Spring Boot在 Spring Boot 上使用 OAuth2 保护特定资源 id
【发布时间】:2018-07-17 23:24:41
【问题描述】:

我在 Spring Boot 上有一个有效的 OAUTH2 实现,AuthorizationServer 和 ResourceServer 在同一个实现上,使用密码授权。 关于服务器:

  • TokenStore 是自定义的,使用 WebService 远程存储令牌。
  • 我有一个自定义的 AuthenticationProvider。

这适用于根据给定权限控制对资源的访问,例如,在 ResourceServer 配置中:

    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/resource/**")
                .hasAnyAuthority("USER", "ADMIN")
            .antMatchers("/api/admin/**")
                .hasAnyAuthority("ADMIN");
    }

现在,我需要控制 USER 可以访问“/api/resource/1”但不能访问“/api/resource/2”,此 ID 可以更改,我在身份验证期间获取列表。

我尝试将 ID 列表添加到 OAuth2AccessToken 附加信息并在 ResourceServer 配置中添加自定义过滤器,但它总是为空。

那么,如何在不使用 JWT 的情况下实现这一点的正确方法是?

【问题讨论】:

    标签: spring spring-boot oauth


    【解决方案1】:

    经过一番思考和研究,如果有人试图实现类似的目标,我会这样做:

    • 将允许的 ID 映射到权限,例如ID_201 和模块作为角色,所以我会有一个 ROLE_ADMIN。
    • 可以在网络安全表达式中引用路径变量,如here 中所述。所以想法是传递变量(资源id)并检查它是否被允许。

      public class WebSecurity {
         public boolean checkResourceId(Authentication authentication, int id) {
              //check if the list of authorities contains ID_{id}.
         }
      }
      

      在网络安全配置中:

      http
      .authorizeRequests()
              .antMatchers("/resource/{resourceId}/**").access("@webSecurity.checkResourceId(authentication,#resourceId)")
              ...
      

    如果您正在使用 spring-security 4.0.4 使用 Spring Boot,请务必按照 bug 中的报告升级到 4.1.1。

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 2017-08-18
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2012-11-23
      相关资源
      最近更新 更多