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

Man*_*uel 7 java spring spring-security spring-data-jpa

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

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

如果您具有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
...
Run Code Online (Sandbox Code Playgroud)

在SecurityExpressionRoot中定义方法hasAnyRole:

public final boolean hasAnyRole(String... roles) {
    return hasAnyAuthorityName(defaultRolePrefix, roles);
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*die 1

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

这个异常是由 Spring Data 引起的,据我在调试时所见,Spring Data 无法解析 SpEL 中参数数量可变的方法。方法ExtensionAwareEvaluationContextProvider解析器不匹配hasAnyRole(String[])

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

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