【问题标题】:Spring Security - Further Restricting MethodsSpring Security - 进一步的限制方法
【发布时间】:2017-03-08 03:40:31
【问题描述】:

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

@PreAuthorize("#oauth2.hasScope('account.read')")
public void getAccount(int accountId);
{
    //return account
}

这非常适合限制没有account.read权限的用户访问此方法。

现在唯一的问题是 any 拥有此权限的用户可以访问 any 帐户。我想限制用户只能访问他们自己的帐户。我确信这是一个常见的场景。其他应用程序如何处理这个问题?

【问题讨论】:

    标签: spring spring-security spring-security-oauth2


    【解决方案1】:

    那么,这里的问题 - 系统如何知道帐户是否属于用户? 答案是您可能将 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");
        }
    }
    

    更新。可能的改进之一可能是首先获取用户,从中获取 id,然后执行 repository.findByIdAndUserId(accountId, userId) 或类似的操作。 (甚至是 repositoryFindByIdAndUser(accountId, user))

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 2012-12-28
      • 2017-06-08
      • 2013-08-26
      • 2012-08-16
      • 2016-02-16
      • 2014-06-02
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多