java - Spring Security方法规则: returned value contains a Collection

标签 java collections spring-security spring-el

在 Spring Security 中,我想保护包含返回值并使用 @PostAuthorize 的方法。

我想添加一个约束,不允许一个用户访问他们不是所有者的资源。我面临的问题是我想根据一组值检查主体 id。

场景:

域对象:

public class Car implements Serializable {
    private Integer id;
    private Collection<Driver> drivers;
    ...
}

public class Driver implements Serializable {
    private Integer id;
    ...
}

服务:

@PostAuthorize("hasRole('ROLE_ADMIN') or principal.id == returnObject.drivers.driver.id")
public Car getCar(int id) throws DAOException {
    ...        
    return carDAO.get(id);
}

当然这个 Spel 表达式不起作用。

SEVERE: El Servlet.service() para el servlet [dispatcher] en el contexto con ruta [] lanzó la excepción [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression 'hasRole('ROLE_ADMIN') or principal.id == returnObject.drivers.driver.id'] con causa raíz
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 42): Field or property 'driver' cannot be found on object of type 'org.eclipse.persistence.indirection.IndirectList'

我还没有看到任何适用于集合的示例。 This unsolved question类似,但我不知道是否符合我的特定场景。 可以做类似的事情吗? 这是做我想做的事情的另一种方式吗?

最佳答案

尝试按如下方式重写您的表达式:

@PostAuthorize("hasRole('ROLE_ADMIN') or returnObject.hasDriverWithId(principal.id)")

然后将相应的hasDriverWithId方法添加到您的Car类中

关于java - Spring Security方法规则: returned value contains a Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416313/

相关文章:

java - Android FragmentManager BackStackRecord.run 抛出 NullPointerException

scala - 如何在多个字段上动态排序 scala 列表

java - 删除最老条目

java - 如何根据 Java 中给定的一组比较器对作为字符串的 TreeMap 键进行排序

java - SpelEvaluationException : EL1004E:(pos 0): Method call: Method hasPermission(java. lang.String) 在 MethodSecurityExpressionRoot 类型上找不到

spring - 当我尝试运行 spring security hello world 示例时,Tomcat 7 服务器无法启动

java - JDBC 不会更新 PostgreSQL 数据库

java - 为什么 jvm 中的默认 hashCode 生成在 JDK 8 中切换为 xor-shift?

angularjs - 如何处理 Spring Boot Angular 应用程序安全

java - 根据映射内映射的键检索值