knel knel - 6 months ago 86
Java Question

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

In Spring Security:

<sec:http pattern="/api/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>


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')" />


or:

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

Answer

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

Comments