SpringSecurity项目如何实现角色包含关系(角色继承)
发布日期:2021-06-29 15:52:31 浏览次数:2 分类:技术文章

本文共 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.

大致意思是这样的,假设我们的项目有两个角色adminuser,我们希望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)所示:

在这里插入图片描述图1

Spring Security中有关AccessDecisionManager的类图

在这里插入图片描述图2

转载地址:https://console.blog.csdn.net/article/details/116562921 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JNI,java调用c++代码入门
下一篇:Spring Security认证成功或失败的事件监听

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月12日 02时43分20秒