igo
igo

Reputation: 6828

Spring Securiy: Allow admin to do everything

How do I allow admin (user with role ROLE_ADMIN) to access everything without explicitly mentioning him in every expression? Currently I have my controller's methods annotated as

@PreAuthorize("(hasRole('ROLE_VENDOR') and hasPermission(#product, 'admin')) or hasRole('ROLE_ADMIN')")

but I want to have it simple like this while allowing admin to do anything:

@PreAuthorize("hasRole('ROLE_VENDOR') and hasPermission(#product, 'admin')")

Is it possible? How do I do that? Important to note that hasPermission(#product, ...) is evaluated to false for admin.

Upvotes: 4

Views: 1437

Answers (3)

ben75
ben75

Reputation: 28706

Use hierarchical role.

Here is a typical configuration:

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
    class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_STAFF
            ROLE_STAFF > ROLE_USER
            ROLE_USER > ROLE_GUEST
        </value>
    </property>
</bean>

reference

Edit

You probably also need to write a custom PermissionEvaluator. If you don't already have one: just extends AclPermissionEvaluator and overwrite only hasPermission to return true as soon as the user have the admin role; otherwise return super.hasPermission(...)

Configure your beans like this:

<security:global-method-security pre-post-annotations="enabled">
     <security:expression-handler ref="expressionHandler" />
</security:global-method-security>

<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
   <property name="permissionEvaluator" ref="customPermissionEvaluator" />
   ... 
</bean>

Upvotes: 2

smajlo
smajlo

Reputation: 972

Try this in security-config

<http use-expressions="true">
    // your security patterns
    <intercept-url pattern="/**" access="hasRole('admin')" />

</http>

If you put this pattern at the end of the list, after checking all rules and not matchning any pattern at the end spring will allow admin send request on any address which equals any controller in practice

Upvotes: 1

Jukka
Jukka

Reputation: 4663

Grant administrators all the necessary roles or use hierarchical roles as described here.

Upvotes: 1

Related Questions