mariubog / oauth-client-sample

sample app connecting to REST service secured with Oauth2
36 stars 26 forks source link

Question - how to restrict scope based method execution in Oauth2? #3

Open sridhar1982 opened 9 years ago

sridhar1982 commented 9 years ago

how to restrict access to methods based on scopes? For example, in the below curl, we get access token that has only scope of "read". That is, user has authorized the client application with read only acess to resources

curl -X POST -vu user_member: http://localhost:9001/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read" 

Now, imagine this 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;
    }
}
mariubog commented 9 years ago

I have not done it, but documentation for Spring Oauth says that "access to protected resources is handled by standard Spring Security request filters" so my guess would be something like this might work http://docs.spring.io/spring-security/site/docs/4.0.3.CI-SNAPSHOT/reference/htmlsingle/#jc-method I am actually curious if it works for authorization specific to oauth and its filter chain. You can also make oauth scopes match with user roles, you should really look it up in docs. http://projects.spring.io/spring-security-oauth/docs/oauth2.html

But this question has nothing to do with the example in this repo.

sridhar1982 commented 9 years ago

Thanks, yes this question has nothing to do with the example in this repo. But since you are very knowledgable in spring-oauth2, I asked you! Thanks anyway