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

↘锁芯ラ 提交于 2019-11-29 14:06:29

问题


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.

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() {
    // ...
  }
}

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


回答1:


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')")

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

The downside is that OAuth2MethodSecurityExpressionHandler extends the DefaultMethodSecurityExpressionHandler and thus you cannot combine it with other classes that also extend this class.

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



来源:https://stackoverflow.com/questions/33638850/how-to-protect-spring-security-oauth-resources-using-preauthorize-based-on-scop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!