how to restrict access to methods based on scopes? For example, in the below curl, I get access token that has only scope of "read". That is, user has authorized the client application with read only access to resources
curl -X POST -vu clientapp:12334 http://localhost:9001/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read"
But Note client is registered with auth server for two scopes - read and write
.
Now, imagine the resource server has two endpoints
/users/update
- this endpoint is a POST request. This should be exposed only if "write" scope is approved by the user.
users/getInfo
- this endpoint is a GET request. This should be exposed because the user has granted client access with read scope
My question is how we control these access at method levels
@RestController
@RequestMapping("/users")
public class UserController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/update", method = RequestMethod.POST)
public UserProfile update(@AuthenticationPrincipal User user) {
///update userProfile
return userProfile;
}
@RequestMapping("/getInfo", method = RequestMethod.GET)
public UserProfile getProfile(@AuthenticationPrincipal User user) {
//get the userData from database
return userProfile;
}
}
Is it possible to annotate methods with scopes: eg
@scope("read")
@RequestMapping("/getInfo", method = RequestMethod.GET)
public UserProfile getProfile(@AuthenticationPrincipal User user) {
//get the userData from database
return userProfile;
}
}
Spring Security OAuth has its own expression e.g. #oauth2.clientHasRole, #oauth2.clientHasAnyRole, #oauth2.hasScope
@PreAuthorize("#oauth2.hasScope('write')")
public void create(Contact contact);
Reference :
http://projects.spring.io/spring-security-oauth/docs/oauth2.html
http://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/provider/expression/OAuth2SecurityExpressionMethods.html
http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/#el-access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With