Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security access with multiple roles

Tags:

I want to define access for some pages for user who has one of following roles (ROLE1 or ROLE2)

I'm trying to configure this in my spring security xml file as following:

<security:http entry-point-ref="restAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security" use-expressions="true">
        <!-- skipped configuration -->
        <security:intercept-url pattern="/rest/api/myUrl*" access="hasRole('ROLE1') or hasRole('ROLE2')" />

        <!-- skipped configuration -->
    </security:http>

I've tried various ways like:

access="hasRole('ROLE1, ROLE2')"
access="hasRole('ROLE1', 'ROLE2')"
access="hasAnyRole('[ROLE1', 'ROLE2]')"

etc

but nothing seems to be working.

I'm keep getting exception

java.lang.IllegalArgumentException: Unsupported configuration attributes:

or

java.lang.IllegalArgumentException: Failed to parse expression 'hasAnyRole(['ROLE1', 'ROLE2'])'

how should it be configured?

Thanks

like image 468
Evgeny Makarov Avatar asked Jun 03 '14 08:06

Evgeny Makarov


People also ask

What is difference between hasRole and hasAuthority?

The main difference is that roles have special semantics. Starting with Spring Security 4, the 'ROLE_' prefix is automatically added (if it's not already there) by any role related method. So hasAuthority('ROLE_ADMIN') is similar to hasRole('ADMIN') because the 'ROLE_' prefix gets added automatically.

How does hasRole works in Spring Security?

By default, Spring Security uses a thread-local copy of this class. This means each request in our application has its security context that contains details of the user making the request. To use it, we simply call the static methods in SecurityContextHolder: Authentication auth = SecurityContextHolder.

Can we have two WebSecurityConfigurerAdapter?

When using Java configuration, the way to define multiple security realms is to have multiple @Configuration classes that extend the WebSecurityConfigurerAdapter base class – each with its own security configuration. These classes can be static and placed inside the main config.


1 Answers

How try with , separate. See doc here and here.

<security:intercept-url pattern="/rest/api/myUrl*" access="ROLE1,ROLE2"/>

OR

hasAnyRole('ROLE1','ROLE2')
like image 81
Wundwin Born Avatar answered Sep 27 '22 21:09

Wundwin Born