我有一个 RESTful 服务,可以公开 /user/{id}
现在,用户可以提供凭据、获取 token 并访问资源。但是,一旦通过身份验证,用户就可以访问任何 id
的资源。
意思是,user1可以访问/user/1
以及user/2
等URI。我最终在 Controller 方法中使用了 Principal
,并开始使用 id
检查 Principal
的 id
用户正在尝试访问。
此外,用户拥有多个与其关联的资源。假设,user1 拥有 res1 和 res2,user2 拥有 res3 和 res4。这些可以通过 /user/1/res/2
访问。我需要一种方法来阻止 /user/1/res/3
因为 res3 属于 user1 而不是 user2。
但我相信这个问题很常见,而且我不太相信我的解决方案。
有没有更好的方法来处理这个问题?
谢谢
最佳答案
如果所有用户只能访问自己的 ID,则根本不应该公开资源 /user/{id}
。
如果我理解正确的话,只需公开 /user
就足够了,从主体或 session 等中查找用户的 ID 并返回结果。
如果您确实想要这样做,您可以自定义实现@PreAuthorize。从博客中获取此代码。
@PreAuthorize("isUsersRes(#id)")
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}")
public UsersfindById(@PathVariable long id) {
return Users.findOne(id);
}
公共(public)类 CustomMethodSecurityExpressionRoot 扩展 SecurityExpressionRoot 实现 MethodSecurityExpressionOperations {
public CustomMethodSecurityExpressionRoot(Authentication authentication) {
super(authentication);
}
以及 isUsersRes 的实现
public class CustomMethodSecurityExpressionRoot
extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
public boolean isMember(Long OrganizationId) {
//user logic
}
查看完整博客 here
关于java - 在 Spring 中保护 REST 资源的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257410/