新闻中心
这篇文章主要讲解了“Spring Security权限管理的投票器与表决机制怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Security权限管理的投票器与表决机制怎么实现”吧!
成都创新互联公司成立与2013年,先为赤城等服务建站,赤城等地企业,进行企业商务咨询服务。为赤城企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
1.投票器
先来看投票器。
在 Spring Security 中,投票器是由 AccessDecisionVoter 接口来规范的,我们来看下 AccessDecisionVoter 接口的实现:
可以看到,投票器的实现有好多种,我们可以选择其中一种或多种投票器,也可以自定义投票器,默认的投票器是 WebExpressionVoter。
我们来看 AccessDecisionVoter 的定义:
public interface AccessDecisionVoter{ int ACCESS_GRANTED = 1; int ACCESS_ABSTAIN = 0; int ACCESS_DENIED = -1; boolean supports(ConfigAttribute attribute); boolean supports(Class clazz); int vote(Authentication authentication, S object, Collectionattributes); }
我稍微解释下:
首先一上来定义了三个常量,从常量名字中就可以看出每个常量的含义,1 表示赞成;0 表示弃权;-1 表示拒绝。两个 supports 方法用来判断投票器是否支持当前请求。vote 则是具体的投票方法。在不同的实现类中实现。三个参数,authentication 表示当前登录主体;object 是一个 ilterInvocation,里边封装了当前请求;attributes 表示当前所访问的接口所需要的角色集合。
我们来分别看下几个投票器的实现。
1.1 RoleVoter
RoleVoter 主要用来判断当前请求是否具备该接口所需要的角色,我们来看下其 vote 方法:
public int vote(Authentication authentication, Object object, Collectionattributes) { if (authentication == null) { return ACCESS_DENIED; } int result = ACCESS_ABSTAIN; Collection authorities = extractAuthorities(authentication); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; for (GrantedAuthority authority : authorities) { if (attribute.getAttribute().equals(authority.getAuthority())) { return ACCESS_GRANTED; } } } } return result; }
这个方法的判断逻辑很简单,如果当前登录主体为 null,则直接返回 ACCESS_DENIED 表示拒绝访问;否则就从当前登录主体 authentication 中抽取出角色信息,然后和 attributes 进行对比,如果具备 attributes 中所需角色的任意一种,则返回 ACCESS_GRANTED 表示允许访问。例如 attributes 中的角色为 [a,b,c],当前用户具备 a,则允许访问,不需要三种角色同时具备。
另外还有一个需要注意的地方,就是 RoleVoter 的 supports 方法,我们来看下:
public class RoleVoter implements AccessDecisionVoter