java 如何基于Scope使用@PreAuthorize保护spring-security-oauth资源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33638850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:56:19  来源:igfitidea点击:

How to protect spring-security-oauth resources using @PreAuthorize based on Scope?

javaspringspring-security-oauth2

提问by yankee

I successfully configured spring-security-oauth2 so that external apps can authenticate with my application. However based on the external app and based on what the user allows, only a subset of my API should be accessible to clients. The available subset is determined by the OAuth Scopes.

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

In classic Spring applications I could use @PreAuthorize to enforce boundaries based on roles:

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

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

How do I do the same when using OAuth and with Scopes instead of roles?

使用 OAuth 和作用域而不是角色时如何做同样的事情?

回答by yankee

Spring OAuth ships with the OAuth2MethodSecurityExpressionHandler, a class that adds the ability to do such checks using the @PreAuthorize expressions. All you need to do is register this class, e.g. like this if you are using Javaconfig:

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

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

Now you can simply use:

现在您可以简单地使用:

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

to secure your request methods. To see which further methods are available besided hasScopecheck the class OAuth2SecurityExpressionMethods.

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

The downside is that OAuth2MethodSecurityExpressionHandlerextends the DefaultMethodSecurityExpressionHandlerand thus you cannot combine it with other classes that also extend this class.

缺点是OAuth2MethodSecurityExpressionHandler扩展了DefaultMethodSecurityExpressionHandler,因此您不能将它与也扩展此类的其他类结合使用。

As an alternative you could also map OAuth scopes to classic user roles.

作为替代方案,您还可以将 OAuth 范围映射到经典用户角色