如何使用基于Scope的@PreAuthorize保护spring-security-oauth资源? [英] How to protect spring-security-oauth resources using @PreAuthorize based on Scope?
问题描述
我成功配置了spring-security-oauth2,以便外部应用程序可以通过我的应用程序进行身份验证.但是,基于外部应用程序和用户所允许的内容,客户端只能访问我的API的子集.可用子集由OAuth范围确定.
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应用程序中,我可以使用@PreAuthorize来基于角色强制执行边界:
In classic Spring applications I could use @PreAuthorize to enforce boundaries based on roles:
@Controller
public class MyController {
@PreAuthorize("hasRole('admin')")
@RequestMapping("...")
public String doStuff() {
// ...
}
}
在使用OAuth并使用Scope(而不是角色)时,我该怎么做?
How do I do the same when using OAuth and with Scopes instead of roles?
推荐答案
Spring OAuth随OAuth2MethodSecurityExpressionHandler
一起提供,该类添加了使用@PreAuthorize表达式进行此类检查的功能.您需要做的就是注册此类,例如如果您使用的是Javaconfig,则如下所示:
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:
@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')")
保护您的请求方法.要查看还有哪些其他方法可用,请检查OAuth2SecurityExpressionMethods
类.
to secure your request methods. To see which further methods are available besided hasScope
check the class OAuth2SecurityExpressionMethods
.
缺点是OAuth2MethodSecurityExpressionHandler
扩展了DefaultMethodSecurityExpressionHandler
,因此您无法将其与也扩展了该类的其他类结合使用.
The downside is that OAuth2MethodSecurityExpressionHandler
extends the DefaultMethodSecurityExpressionHandler
and thus you cannot combine it with other classes that also extend this class.
您也可以将OAuth范围映射到经典用户角色.
这篇关于如何使用基于Scope的@PreAuthorize保护spring-security-oauth资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!