本文共 2041 字,大约阅读时间需要 6 分钟。
近期在阅读 Spring Security 官方文档时发现关于 Hierarchical Roles
的介绍,大致内容如下:
It is a common requirement that a particular role in an application should automatically “include” other roles. For example, in an application which has the concept of an “admin” and a “user” role, you may want an admin to be able to do everything a normal user can. To achieve this, you can either make sure that all admin users are also assigned the “user” role. Alternatively, you can modify every access constraint which requires the “user” role to also include the “admin” role. This can get quite complicated if you have a lot of different roles in your application.
The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. An extended version of Spring Security’s RoleVoter, RoleHierarchyVoter, is configured with a RoleHierarchy, from which it obtains all the “reachable authorities” which the user is assigned.
大致意思是这样的,假设我们的项目有两个角色admin
和user
,我们希望admin
权限包含user
权限,可以有两种解决方法:
admin
角色权限的用户同时分配user
角色; ②所有需要user
角色权限的资源同时设置需要admin
角色权限 这样做适合角色较少的情况,当应用的角色很多时,这样做会导致开发的混乱,权限信息复杂。 这时可以使用Spring Security提供的Hierarchical Roles
,分级(层次)角色,系统使用RoleHierarchy
构建一个RoleHierarchyVoter
用于权限管理时投票。
项目配置
官方文档中只提到注入一个RoleVoter
的Bean,并没有说其他配置
ROLE_ADMIN > ROLE_STAFF ROLE_STAFF > ROLE_USER ROLE_USER > ROLE_GUEST
(※)实际操作使用配置类方法@Bean注入,发现并不会生效,参考了很多博客,最后发现只需要注入一个RoleHierarchy
即可,
@Beanpublic RoleHierarchy roleHierarchy(){ /** * 定义用户角色包含关系字符串 */ String roleRules="ROLE_admin > ROLE_staff\n" + "ROLE_staff > ROLE_user\n"+ "ROLE_user > ROLE_guest\n"+ "ROLE_guest > ROLE_authenticated"; //角色层次关系对象 RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); roleHierarchy.setHierarchy(roleRules); return roleHierarchy;}
注意:角色继承关系字符串必须使用’\n’换行,’>'前后必须有空格
底层实现
和授权管理相关的类较多,例如RoleVoter
AccessDecisionManager
等,Spring Security处理授权的流程如图(1)所示:
Spring Security中有关AccessDecisionManager
的类图
转载地址:https://console.blog.csdn.net/article/details/116562921 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!