knel knel - 8 months ago 121
Java Question

Spring Security , access="ROLE_ADMIN" Vs access="hasAnyRole('ROLE_ADMIN')

In Spring Security:

<sec:http pattern="/api/**" create-session="never"
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />

in this line
<intercept-url pattern="/api/**" access="ROLE_ADMIN" />

What is difference meaning if I write:

<intercept-url pattern="/api/**" access="hasRole('ROLE_ADMIN')" />


<intercept-url pattern="/api/**" access="hasAnyRole('ROLE_ADMIN')" />


As Spring Security documentation states:

hasRole([role]): Returns true if the current principal has the specified role

hasAnyRole([role1,role2]): Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings).

Also, on access attribute, documentation states:

access: Lists the access attributes which will be stored in the FilterInvocationSecurityMetadataSource for the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).

But in your case, you're passing a single element list to the hasAnyRole, So:

access="ROLE_ADMIN" Vs access="hasAnyRole('ROLE_ADMIN')

hasRole('ROLE_ADMIN') and hasAnyRole('ROLE_ADMIN') are identical and both means that the current principal should have the ROLE_ADMIN authority.

(a "principal" generally means a user, device or some other system which can perform an action in your application).