+-
如何在@Query中使用hasAnyRole表达式SpEl

我在@Query中使用Spring Security Expressions就像这个例子:

@Query("select o from Pet o where o.owner.name like ?#{hasRole('ROLE_ADMIN') ? '%' : principal.username}")

如果您具有ADMIN角色,则查询将返回所有宠物。但是,如果您没有此角色,则查询仅返回所有者名称与用户身份验证名称相同的Pet对象。

这很好用,但是当我尝试使用hasAnyRole('ROLE_ADMIN','ROLE_OWNER')时,系统会返回异常...

org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 0): Method call: Method hasAnyRole(java.lang.String,java.lang.String) cannot be found on java.lang.Object[] type
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMetho
...

在SecurityExpressionRoot中定义方法hasAnyRole:

public final boolean hasAnyRole(String... roles) {
    return hasAnyAuthorityName(defaultRolePrefix, roles);
}
0
投票

我有同样的问题,快速的解决方法是写hasRole('ROLE_SUPER') or hasRole('ROLE_OWNER')

此异常是由Spring Data引起的,就调试问题而言,它无法在SpEL中解析具有可变数量参数的方法。 ExtensionAwareEvaluationContextProvider方法解析器与hasAnyRole(String[])不匹配。

我创造了https://jira.spring.io/browse/DATACMNS-1518。

编辑:这个问题已得到修复,我刚刚测试了最新的快照并得到了hasAnyRole的工作。