Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use hasAnyRole like expression SpEl in @Query

I'm using Spring Security Expressions within @Query like this example:

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

If you have the role ADMIN, the query returns all the pets. But if you don't have this role, the query returns only Pet objects where the owner name is the same of the user authenticated name.

This works fine, but when I try to use hasAnyRole('ROLE_ADMIN','ROLE_OWNER'), the system returns an exception...

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
...

In SecurityExpressionRoot is defined the method hasAnyRole:

public final boolean hasAnyRole(String... roles) {
    return hasAnyAuthorityName(defaultRolePrefix, roles);
}
like image 745
Manuel Avatar asked Feb 18 '16 16:02

Manuel


1 Answers

I have the same issue, the quick workaround is to write hasRole('ROLE_SUPER') or hasRole('ROLE_OWNER').

This exception is caused by Spring Data, which is not able to resolve methods with a variable number of arguments in SpEL, as far as I can see when debugging. The ExtensionAwareEvaluationContextProvider method resolver doesn't match hasAnyRole(String[]).

I created https://jira.spring.io/browse/DATACMNS-1518.

EDIT: this issue has been fixed, I just tested latest snapshot and got hasAnyRole work.

like image 159
Patrice Blanchardie Avatar answered Sep 29 '22 21:09

Patrice Blanchardie