Spring安全性-进一步限制方法

Spring安全性-进一步限制方法,spring,spring-security,spring-security-oauth2,Spring,Spring Security,Spring Security Oauth2,我有一个应用程序正在使用Spring Security授权OAuth2令牌。使用@PreAuthorize标记,我可以轻松确保用户在允许他们访问方法之前拥有权限: @PreAuthorize("#oauth2.hasScope('account.read')") public void getAccount(int accountId); { //return account } 这非常适用于限制没有帐户的用户。读取访问此方法的权限 唯一的问题是现在任何拥有此权限的用户都可以访问任何帐

我有一个应用程序正在使用Spring Security授权OAuth2令牌。使用@PreAuthorize标记,我可以轻松确保用户在允许他们访问方法之前拥有权限:

@PreAuthorize("#oauth2.hasScope('account.read')")
public void getAccount(int accountId);
{
    //return account
}
这非常适用于限制没有帐户的用户。读取访问此方法的权限


唯一的问题是现在任何拥有此权限的用户都可以访问任何帐户。我想限制用户只访问他们自己的帐户。我相信这是一种常见的情况。其他应用程序如何处理这个问题呢?

所以,这里的问题是——系统如何知道这个帐户是否属于用户? 答案可能是您正在数据库中存储UserAccount关系。最简单的解决方案是在方法中正确执行检查:

@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,然后创建一个存储库。findByIdAndUserId(accountId,userId)或类似的东西。(甚至是repositoryFindByIdAndUser(accountId,user))

所以,这里的问题是——系统如何知道帐户是否属于用户? 答案可能是您正在数据库中存储UserAccount关系。最简单的解决方案是在方法中正确执行检查:

@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,然后创建一个存储库。findByIdAndUserId(accountId,userId)或类似的东西。(甚至是repositoryFindByIdAndUser(accountId,user))