Spring 安全 - 进一步限制方法
Spring Security - Further Restricting Methods
我有一个应用程序正在授权具有 Spring 安全性的 OAuth2 令牌。使用 @PreAuthorize 标记,我可以轻松地确保用户在允许他们访问方法之前拥有权限:
@PreAuthorize("#oauth2.hasScope('account.read')")
public void getAccount(int accountId);
{
//return account
}
这对于限制没有 account.read 权限的用户访问此方法非常有效。
现在唯一的问题是任何具有此权限的用户可以访问任何帐户。我想限制用户只能访问他们自己的帐户。我敢肯定这是一个常见的情况。其他应用程序如何处理这个问题?
那么,这里的问题 - 系统如何知道帐户是否属于用户?
答案是您可能将 User<->Account 关系存储在数据库中。最简单的解决方案是在您的方法中正确进行检查:
@PreAuthorize("#oauth2.hasScope('account.read')")
public Account getAccount(int accountId) {
// get account from db
Account account = repository.findById(accountId);
// you will need a little helper to get your User from
//Spring SecurityContextHolder or whatever there for oauth2
User user = securityManager.getCurrentUser();
if (account.belongs(user)) {
return account;
} else {
throw new UnathorizedException("User is not authorized to view account");
}
}
Upd. 可能的改进之一可能是首先获取用户,从中获取 id 并执行 repository.findByIdAndUserId(accountId, userId) 或类似的操作. (甚至 repositoryFindByIdAndUser(accountId, user))
我有一个应用程序正在授权具有 Spring 安全性的 OAuth2 令牌。使用 @PreAuthorize 标记,我可以轻松地确保用户在允许他们访问方法之前拥有权限:
@PreAuthorize("#oauth2.hasScope('account.read')")
public void getAccount(int accountId);
{
//return account
}
这对于限制没有 account.read 权限的用户访问此方法非常有效。
现在唯一的问题是任何具有此权限的用户可以访问任何帐户。我想限制用户只能访问他们自己的帐户。我敢肯定这是一个常见的情况。其他应用程序如何处理这个问题?
那么,这里的问题 - 系统如何知道帐户是否属于用户? 答案是您可能将 User<->Account 关系存储在数据库中。最简单的解决方案是在您的方法中正确进行检查:
@PreAuthorize("#oauth2.hasScope('account.read')")
public Account getAccount(int accountId) {
// get account from db
Account account = repository.findById(accountId);
// you will need a little helper to get your User from
//Spring SecurityContextHolder or whatever there for oauth2
User user = securityManager.getCurrentUser();
if (account.belongs(user)) {
return account;
} else {
throw new UnathorizedException("User is not authorized to view account");
}
}
Upd. 可能的改进之一可能是首先获取用户,从中获取 id 并执行 repository.findByIdAndUserId(accountId, userId) 或类似的操作. (甚至 repositoryFindByIdAndUser(accountId, user))