【问题标题】:Custom permissions in Spring Security - targetId nullSpring Security 中的自定义权限 - targetId null
【发布时间】:2012-09-01 06:56:42
【问题描述】:

我正在使用基于表达式的 Spring Security 3.x 保护我的应用程序。我有以下服务接口:

@PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#employeeId, 'employee', 'isOwner')")
EmployeeData getById(Integer employeeId);

@PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#employeeId, 'employee', 'isOwner')")
void update(Integer employeeId, EmployeeData employeedata);

我的 PermissionEvaluator 如下所示:

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
    private Map<String, Permission> permissionMap = new HashMap<String, Permission>();

    public CustomPermissionEvaluator(Map<String, Permission> permissionMap) {
        this.permissionMap = permissionMap;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        throw new PermissionNotDefinedException("Permission not supported for loaded domain object by " + this.getClass().toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        verifyPermissionIsDefined((String) permission);
        return permissionMap.get(permission).isAllowed(authentication, (Integer) targetId);
    }

    private void verifyPermissionIsDefined(String permissionKey) {
        if (!permissionMap.containsKey(permissionKey)) {
            throw new PermissionNotDefinedException("No permission with key '" + permissionKey + "' is defined in" + this.getClass().toString());
        }
    }
}

对于第一个服务方法 (getById),它可以正常工作:

  • 如果用户拥有 ROLE_ADMIN,那么他就可以获取数据。
  • 如果用户想查看自己的个人资料,他也可以查看

但是,对于第二种方法,更新方法,应用程序不起作用。 targetId 在调用hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) 方法时始终为空。

我不知道为什么。任何帮助将不胜感激。

【问题讨论】:

    标签: spring spring-security


    【解决方案1】:

    请检查服务和实现中的参数名称是否匹配。

    您还可以检查 MethodSecurityEvaluationContext.lookupVariable 方法如何与调试器一起使用。

    查看类似问题:spring security : Why can't we access Hibernate entitiy parameters in @PreAuthorize?

    【讨论】:

    • 这为我指明了正确的方向。这是服务实施中的一个错字。非常感谢!
    【解决方案2】:

    我有类似的问题:targetDomainObject 每次 hasPermission 调用都为 null。

    对我来说,问题是我的接口 A 设置了所有身份验证注释(如 @PreAuthorize 和 @PostAuthorize)。它由抽象类 B 实现。具体类 C 是实际的服务。

    public class C extends B
    

    这不起作用。

    public class C extends B implements A
    

    但这很好用。

    从代码逻辑来看,这些声明是完全一样的。但是 Spring 安全性首先混淆了
    并与第二个正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 2010-11-02
      • 1970-01-01
      • 2016-04-23
      • 2014-06-02
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多