Spring Security:允许管理员完成所有工作

时间:2013-10-01 19:49:21

标签: java spring spring-security

如何在没有在每个表达式中明确提及他的情况下允许admin(具有角色ROLE_ADMIN的用户)访问所有内容?目前我的控制器方法注释为

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

但是我想让管理员做任何事情都这样简单:

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

有可能吗?我怎么做?需要注意的是,对于admin,hasPermission(#product,...)被评估为false。

3 个答案:

答案 0 :(得分:2)

使用分层角色。

以下是典型配置:

<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

修改

您可能还需要编写自定义PermissionEvaluator。如果您还没有:仅扩展AclPermissionEvaluator并仅覆盖hasPermission,只要用户具有admin角色,就会返回true;否则返回super.hasPermission(...)

像这样配置你的bean:

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

答案 1 :(得分:1)

向管理员授予所有必要的角色或使用所述here所述的分层角色。

答案 2 :(得分:1)

在security-config

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

</http>

如果你把这个模式放在列表的末尾,在检查完所有规则并且在结束弹簧上没有匹配任何模式后,允许admin发送任何地址等于任何控制器的请求