How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?
There is a special security expression in spring security:
hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).
I have never used it but I think it is exactly what you are looking for.
Example usage:
<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
...
</security:authorize>
Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.
@dimas's answer is not logically consistent with your question; ifAllGranted
cannot be directly replaced with hasAnyRole
.
From the Spring Security 3—>4 migration guide:
Old:
<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
New (SPeL):
<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
Replacing ifAllGranted
directly with hasAnyRole
will cause spring to evaluate the statement using an OR
instead of an AND
. That is, hasAnyRole
will return true
if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted
method only returned true
if the authenticated principal contained all of the specified roles.
TL;DR: To replicate the behavior of ifAllGranted
using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2')
pattern needs to be used.