如何在SpringRESTOAuth中限制基于oauth作用域的方法访问?

如何在SpringRESTOAuth中限制基于oauth作用域的方法访问?,spring,spring-security,spring-security-oauth2,Spring,Spring Security,Spring Security Oauth2,如何限制对基于作用域的方法的访问? 例如,在下面的示例中,我得到的访问令牌的作用域仅为“read”。也就是说,用户已授权客户端应用程序以只读方式访问资源 curl-X POST-vu客户pp:12334http://localhost:9001/oauth/token -H“Accept:application/json”-d“password=spring&username=roy&grant\u type=password&scope=read” 但请注意,客户端在auth服务器上注册了

如何限制对基于作用域的方法的访问? 例如,在下面的示例中,我得到的访问令牌的作用域仅为“read”。也就是说,用户已授权客户端应用程序以只读方式访问资源


curl-X POST-vu客户pp:12334http://localhost:9001/oauth/token -H“Accept:application/json”-d“password=spring&username=roy&grant\u type=password&scope=read”

但请注意,客户端在auth服务器上注册了两个作用域-
读和写

现在,假设资源服务器有两个端点

/users/update
-此端点是POST请求。仅当用户批准“写入”范围时,才应公开此内容

users/getInfo
-此端点是一个GET请求。这应该公开,因为用户已授予具有读取范围的客户端访问权限

我的问题是我们如何在方法级别控制这些访问

@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;
    }
}
是否可以使用作用域注释方法:例如

  @scope("read")
   @RequestMapping("/getInfo",  method = RequestMethod.GET)
    public UserProfile getProfile(@AuthenticationPrincipal User user) {

            //get the userData from database
            return userProfile;
    }
}

Spring Security OAuth有自己的表达式,例如#oauth2.clientHasRole、#oauth2.clientHasAnyRole、#oauth2.hasScope

@PreAuthorize("#oauth2.hasScope('write')")
public void create(Contact contact);
参考: