How to protect spring-security-oauth resources with @PreAuthorize based on scope?

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

In classic Spring applications, I could use @PreAuthorize to enforce role-based bounds:

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

How to do the same when using OAuth and Scope instead of roles?

+6
java spring spring-security-oauth2
source share
1 answer

Spring OAuth comes with OAuth2MethodSecurityExpressionHandler , a class that adds the ability to perform such checks using @PreAuthorize expressions. All you have to do is register this class, for example. for example if you use 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 protect your request methods. To find out what additional methods are available for hasScope , check the OAuth2SecurityExpressionMethods class.

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

Alternatively, you can also map OAuth scopes to classic user roles .

+12
source share

All Articles