【问题标题】:How to protect spring-security-oauth resources using @PreAuthorize based on Scope?如何使用基于Scope的@PreAuthorize保护spring-security-oauth资源?
【发布时间】:2016-02-11 20:29:03
【问题描述】:

我成功配置了 spring-security-oauth2 以便外部应用程序可以通过我的应用程序进行身份验证。但是,基于外部应用程序和用户允许的内容,客户端应该只能访问我的 API 的一个子集。可用子集由 OAuth 范围确定。

在经典的 Spring 应用程序中,我可以使用 @PreAuthorize 来根据角色强制执行边界:

@Controller
public class MyController {
  @PreAuthorize("hasRole('admin')")
  @RequestMapping("...")
  public String doStuff() {
    // ...
  }
}

在使用 OAuth 和 Scopes 而不是角色时,我该如何做同样的事情?

【问题讨论】:

    标签: java spring spring-security-oauth2


    【解决方案1】:

    Spring OAuth 附带 OAuth2MethodSecurityExpressionHandler,该类增加了使用 @PreAuthorize 表达式进行此类检查的能力。您需要做的就是注册这个类,例如如果你使用 Javaconfig,就像这样:

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
    

    现在您可以简单地使用:

    @PreAuthorize("#oauth2.hasScope('requiredScope')")
    

    保护您的请求方法。要查看除了hasScope 之外还有哪些可用的方法,请查看OAuth2SecurityExpressionMethods 类。

    缺点是OAuth2MethodSecurityExpressionHandler 扩展了DefaultMethodSecurityExpressionHandler,因此您不能将它与同样扩展该类的其他类结合起来。

    您也可以map OAuth scopes to classic user roles

    【讨论】:

    • 我使用的是 Spring Boot 1.5.10,#oauth2.hasScope... 可以在不覆盖 createExpressionHandler() 的情况下工作
    • 您知道如何使用@PreAuthorize("#oauth2.hasScope('requiredScope')") 对函数进行单元测试吗?我已经根据其他安全标准对其进行了整理,但我无法弄清楚这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2014-11-03
    • 2013-08-06
    • 2012-12-26
    • 2015-12-11
    • 2011-07-22
    • 2011-06-28
    相关资源
    最近更新 更多