如何使用SpringMVC控制用户身份验证

如何使用SpringMVC控制用户身份验证,spring,authentication,spring-mvc,Spring,Authentication,Spring Mvc,我正在使用SpringMVC3构建一个用户管理器系统 该系统包括以下型号: Department User 各部门具有层次结构,例如: Dep1 SubDep1 SubDep2 Sub_sub_dep1 xxxx 如果获得授权,可以添加/更新/删除部门/用户,但只能在其部门和子部门内执行这些操作 例如,有三个部门(有三个用户): 因此,user1可以执行/add/upate/delete所有用户(user1、user2、user3、user4) 而user3只能为us

我正在使用SpringMVC3构建一个用户管理器系统

该系统包括以下型号:

Department
User
各部门具有层次结构,例如:

Dep1
  SubDep1
  SubDep2
    Sub_sub_dep1
    xxxx
如果获得授权,可以添加/更新/删除部门/用户,但只能在其部门和子部门内执行这些操作

例如,有三个部门(有三个用户):

因此,user1可以执行/add/upate/delete所有用户(user1、user2、user3、user4)

而user3只能为user(user3,user4)执行操作

我可以控制user3在
部门/列表
页面中看不到user1和user2

但是如果他像这样输入url呢:

department/update/1
@PreAuthorize("hasRole('ROLE_USER') and hasPermission(#_dept, 'deptAndSubs')")
public String methodToProtect(String _dept)throws Exception    {
        <custom code>;
    }
必须避免这种情况,因为user1(其id为1)不属于Dep0102或Dep010201


如何控制这一点?

一个选项是创建自定义Spring安全性
PermissionEvaluator
,并在
hasPermission(身份验证、对象targetDomainObject、对象权限)
方法中实现自定义检查

要保护的方法的签名最终如下所示:

department/update/1
@PreAuthorize("hasRole('ROLE_USER') and hasPermission(#_dept, 'deptAndSubs')")
public String methodToProtect(String _dept)throws Exception    {
        <custom code>;
    }
isTargetDeptInUserDeptTree方法是提取用户部门树并验证目标部门是否在其中的自定义代码

最后,您必须设置xml配置:

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

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

<beans:bean id="customPermissionEvaluator" class="....CustomPermissionEvaluator"/>

祝你好运