问题描述
在Spring Security中,我想要确保一个包含返回值并使用 @PostAuthorize
的方法。
In Spring Security I want to secure a method incorporating returned values and using @PostAuthorize
.
我想添加一个限制,不允许一个用户访问他们不是所有者的资源。
I want to add a constraing that will not allow one user to access to resources they are not owners. The problem I face is that I want to check principal id against one collection of values.
情况:
域对象:
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表达式不起作用。
Of course this Spel expression does not works.
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'
我没有看到任何工作在一个集合的例子。
是类似,但我不知道如果匹配我的特定情况。
可以做这样的事情吗?
I haven't seen any example that works over a Collection.This unsolved question is similar but I don't know if matches my particular scenario.Is possible to do something like that?It is another way to do what I am trying to do?
推荐答案
尝试重写你的表达式,如下所示:
Try to rewrite your expression as follows:
@PostAuthorize("hasRole('ROLE_ADMIN') or returnObject.hasDriverWithId(principal.id)")
,然后将相应的 hasDriverWithId
方法添加到您的Car类
and then add corresponding hasDriverWithId
method to your Car class
这篇关于Spring Security方法规则:返回值包含一个Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!