问题
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.
Scenario:
Domain objects:
public class Car implements Serializable {
private Integer id;
private Collection<Driver> drivers;
...
}
public class Driver implements Serializable {
private Integer id;
...
}
Service:
@PostAuthorize("hasRole('ROLE_ADMIN') or principal.id == returnObject.drivers.driver.id")
public Car getCar(int id) throws DAOException {
...
return carDAO.get(id);
}
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?
回答1:
Try to rewrite your expression as follows:
@PostAuthorize("hasRole('ROLE_ADMIN') or returnObject.hasDriverWithId(principal.id)")
and then add corresponding hasDriverWithId
method to your Car class
回答2:
Trying to access the property driver
on a List doesn't really make sense. Are you wanting the first item in the list? What about returnObject.drivers[0].id
?
来源:https://stackoverflow.com/questions/15416313/spring-security-method-rules-returned-value-contains-a-collection