在 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/