最近项目需要用到Spring Security的权限控制,故花了点时间简单的去看了一下其权限控制相关的源码(版本为4.2)。

AccessDecisionManager

spring security是通过AccessDecisionManager进行授权管理的,先来张官方图镇楼。

AccessDecisionManager

AccessDecisionManager 接口定义了如下方法:

//调用AccessDecisionVoter进行投票(关键方法)
void decide(Authentication authentication, Object object,
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException,
InsufficientAuthenticationException; boolean supports(ConfigAttribute attribute);
boolean supports(Class clazz);

接下来看看它的实现类的具体实现:

AffirmativeBased

public void decide(Authentication authentication, Object object,
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) {
//调用AccessDecisionVoter进行vote(我们姑且称之为投票吧),后面再看vote的源码。
int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) {
logger.debug("Voter: " + voter + ", returned: " + result);
} switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED://值为1
//只要有voter投票为ACCESS_GRANTED,则通过
return; case AccessDecisionVoter.ACCESS_DENIED://值为-1
deny++; break; default:
break;
}
} if (deny > 0) {
//如果有两个及以上AccessDecisionVoter(姑且称之为投票者吧)都投ACCESS_DENIED,则直接就不通过了
throw new AccessDeniedException(messages.getMessage(
"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
} // To get this far, every AccessDecisionVoter abstained
checkAllowIfAllAbstainDecisions();
}

源码中,有个Collection configAttributes 参数,ConfigAttribute是什么? 这个其实是一个很灵活的东西,不同的情况代表不同的语义,比如在使用了角色控制的时候,传入的则可能是ROLE__XXX之类的,以便ROLE_VOTER使用。具体的后面在细说。

通过以上代码可直接看到AffirmativeBased的策略:

  • 只要有投通过(ACCESS_GRANTED)票,则直接判为通过。
  • 如果没有投通过票且反对(ACCESS_DENIED)票在两个及其以上的,则直接判为不通过。

UnanimousBased

public void decide(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes) throws AccessDeniedException { int grant = 0;
int abstain = 0; List<ConfigAttribute> singleAttributeList = new ArrayList<ConfigAttribute>(1);
singleAttributeList.add(null); for (ConfigAttribute attribute : attributes) {
singleAttributeList.set(0, attribute); for (AccessDecisionVoter voter : getDecisionVoters()) {
//配置的投票者进行投票
int result = voter.vote(authentication, object, singleAttributeList); if (logger.isDebugEnabled()) {
logger.debug("Voter: " + voter + ", returned: " + result);
} switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED:
grant++; break; case AccessDecisionVoter.ACCESS_DENIED:
//只要有投票者投反对票就立马判为无权访问
throw new AccessDeniedException(messages.getMessage(
"AbstractAccessDecisionManager.accessDenied",
"Access is denied")); default:
abstain++; break;
}
}
} // To get this far, there were no deny votes
if (grant > 0) {
//如果没反对票且有通过票,那么就判为通过
return;
} // To get this far, every AccessDecisionVoter abstained
checkAllowIfAllAbstainDecisions();
}

由此可见UnanimousBased的策略:

  • 无论多少投票者投了多少通过(ACCESS_GRANTED)票,只要有反对票(ACCESS_DENIED),那都判为不通过。
  • 如果没有反对票且有投票者投了通过票,那么就判为通过。

ConsensusBased

public void decide(Authentication authentication, Object object,
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
int grant = 0;
int deny = 0;
int abstain = 0; for (AccessDecisionVoter voter : getDecisionVoters()) {
//配置的投票者进行投票
int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) {
logger.debug("Voter: " + voter + ", returned: " + result);
} switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED:
grant++; break; case AccessDecisionVoter.ACCESS_DENIED:
deny++; break; default:
abstain++; break;
}
} if (grant > deny) {
//通过的票数大于反对的票数则判为通过
return;
} if (deny > grant) {
//通过的票数小于反对的票数则判为不通过
throw new AccessDeniedException(messages.getMessage(
"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
} if ((grant == deny) && (grant != 0)) {
//this.allowIfEqualGrantedDeniedDecisions默认为true
//通过的票数和反对的票数相等,则可根据配置allowIfEqualGrantedDeniedDecisions进行判断是否通过
if (this.allowIfEqualGrantedDeniedDecisions) {
return;
}
else {
throw new AccessDeniedException(messages.getMessage(
"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
}
} // To get this far, every AccessDecisionVoter abstained
checkAllowIfAllAbstainDecisions();
}

由此可见,ConsensusBased的策略:

  • 通过的票数大于反对的票数则判为通过。
  • 通过的票数小于反对的票数则判为不通过。
  • 通过的票数和反对的票数相等,则可根据配置allowIfEqualGrantedDeniedDecisions(默认为true)进行判断是否通过。

到此,应该明白AffirmativeBased、UnanimousBased、ConsensusBased三者的区别了吧,spring security默认使用的是AffirmativeBased, 如果有需要,可配置为其它两个,也可自己去实现。

投票者

以上AccessDecisionManager的实现类都只是对权限(投票)进行管理(策略的实现),具体投票(vote)的逻辑是通过调用AccessDecisionVoter的子类(投票者)的vote方法实现的。spring security默认注册了RoleVoter和AuthenticatedVoter两个投票者。下面来看看其源码。

AccessDecisionManager

boolean supports(ConfigAttribute attribute);
boolean supports(Class<?> clazz);
//核心方法,此方法由上面介绍的的AccessDecisionManager调用,子类实现此方法进行投票。
int vote(Authentication authentication, S object,
Collection<ConfigAttribute> attributes);

RoleVoter

private String rolePrefix = "ROLE_";

//只处理ROLE_开头的(可通过配置rolePrefix的值进行改变)
public boolean supports(ConfigAttribute attribute) {
if ((attribute.getAttribute() != null)
&& attribute.getAttribute().startsWith(getRolePrefix())) {
return true;
}
else {
return false;
}
} public int vote(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes) { if(authentication == null) {
//用户没通过认证,则投反对票
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
//获取用户实际的权限
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication); for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED; // Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
//权限匹配则投通过票
return ACCESS_GRANTED;
}
}
}
}
//如果处理过,但没投通过票,则为反对票,如果没处理过,那么视为弃权(ACCESS_ABSTAIN)。
return result;
}

很简单吧,同时,我们还可以通过实现AccessDecisionManager来扩展自己的voter。但是,要实现这个,我们还必须得弄清楚attributes这个参数是从哪儿来的,这个是个很关键的参数啊。通过一张官方图能很清晰的看出这个问题来:

接下来,就看看AccessDecisionManager的调用者AbstractSecurityInterceptor。

AbstractSecurityInterceptor

...
//上面说过默认是AffirmativeBased,可配置
private AccessDecisionManager accessDecisionManager;
...
protected InterceptorStatusToken beforeInvocation(Object object) {
...
//抽象方法,子类实现,但由此也可看出ConfigAttribute是由SecurityMetadataSource(实际上,默认是DefaultFilterInvocationSecurityMetadataSource)获取。
Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
.getAttributes(object);
...
//获取当前认证过的用户信息
Authentication authenticated = authenticateIfRequired(); try {
//调用AccessDecisionManager
this.accessDecisionManager.decide(authenticated, object, attributes);
}
catch (AccessDeniedException accessDeniedException) {
publishEvent(new AuthorizationFailureEvent(object, attributes, authenticated,
accessDeniedException)); throw accessDeniedException;
}
...
} public abstract SecurityMetadataSource obtainSecurityMetadataSource();

以上方法都是由AbstractSecurityInterceptor的子类(默认是FilterSecurityInterceptor)调用,那就再看看吧:

FilterSecurityInterceptor

...
//SecurityMetadataSource的实现类,由此可见,可通过外部配置。这也说明我们可以通过自定义SecurityMetadataSource的实现类来扩展出自己实际需要的ConfigAttribute
private FilterInvocationSecurityMetadataSource securityMetadataSource;
...
//入口
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
//关键方法
invoke(fi);
} public void invoke(FilterInvocation fi) throws IOException, ServletException {
if ((fi.getRequest() != null)
&& (fi.getRequest().getAttribute(FILTER_APPLIED) != null)
&& observeOncePerRequest) {
// filter already applied to this request and user wants us to observe
// once-per-request handling, so don't re-do security checking
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
}
else {
// first time this request being called, so perform security checking
if (fi.getRequest() != null) {
fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
}
//在这儿调用了父类(AbstractSecurityInterceptor)的方法, 也就调用了accessDecisionManager
InterceptorStatusToken token = super.beforeInvocation(fi); try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
}
finally {
super.finallyInvocation(token);
}
//完了再执行(父类的方法),一前一后,AOP无处不在啊
super.afterInvocation(token, null);
}
}

好啦,到此应该对于Spring Security的权限管理比较清楚了。看完这个,不知你是否能扩展出一套适合自己需求的权限需求来呢,如果还不太清楚,那也没关系,下篇就实战一下,根据它来开发一套自己的权限体系。

欢迎大家访问我的独立博客:

www.javafan.cn

话说Spring Security权限管理(源码)的更多相关文章

  1. Spring Security 登录校验 源码解析

    传统情况下,在过滤器中做权限验证,Spring Secuirty也是在Filter中进行权限验证. 创建并注册过滤器 package com.awizdata.edubank.config; impo ...

  2. Spring Security 架构与源码分析

    Spring Security 主要实现了Authentication(认证,解决who are you? ) 和 Access Control(访问控制,也就是what are you allowe ...

  3. 自定义Spring Security权限控制管理(实战篇)

    上篇<话说Spring Security权限管理(源码)>介绍了Spring Security权限控制管理的源码及实现,然而某些情况下,它默认的实现并不能满足我们项目的实际需求,有时候需要 ...

  4. Spring框架之jms源码完全解析

    Spring框架之jms源码完全解析 我们在前两篇文章中介绍了Spring两大核心IOC(Inversion of Control控制反转)和AOP(Aspect Oriented Programmi ...

  5. Spring框架之spring-webmvc源码完全解析

    Spring框架之spring-webmvc源码完全解析 Spring框架提供了构建Web应用程序的全功能MVC模块.Spring MVC分离了控制器.模型对象.分派器以及处理程序对象的角色,支持多种 ...

  6. Spring框架之事务源码完全解析

    Spring框架之事务源码完全解析   事务的定义及特性: 事务是并发控制的单元,是用户定义的一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位.通过事务将逻辑相关的一组操作绑定在一 ...

  7. 【Spring】Spring IOC原理及源码解析之scope=request、session

    一.容器 1. 容器 抛出一个议点:BeanFactory是IOC容器,而ApplicationContex则是Spring容器. 什么是容器?Collection和Container这两个单词都有存 ...

  8. C#以管理员权限运行源码,C#软件获取管理员权限,c#获取管理员权限

    C#以管理员权限运行源码,C#软件获取管理员权限,c#获取管理员权限 发布时间:2014-10-19 21:40内容来源:未知 点击: 次 windows 7和vista提高的系统的安全性,同时需要明 ...

  9. Spring框架之beans源码完全解析

    导读:Spring可以说是Java企业开发里最重要的技术.而Spring两大核心IOC(Inversion of Control控制反转)和AOP(Aspect Oriented Programmin ...

随机推荐

  1. Linux:-防火墙iptables如何个性化定制?

    身份标签/usr/local/etc/identity,主脚本iptables.sh,附属目录functions/iptables.d ├── iptables.sh ├── functions│   ...

  2. 制作QQ空间的一些想法

    新的项目开始了,这一次是做一个网站类似于QQ空间那样的,基本功能比如说写日志,说说之类的都要有(说说是要有楼中楼嵌套的,应该能够上传图片),还要可以修改个人信息.登录注册之类的更不用说了,还要有一定的 ...

  3. 1.Linux系统安装

    Linux系统安装系统分区(磁盘分区) 主要管理:文件和目录分类:主分区:最多有4个 扩展分区:1个扩展分区 和主分区最多4个 存放逻辑分区 逻辑分区:存放数据 格式化:高级格式化(逻辑格式化) 写入 ...

  4. 使用AFNetWorking读取JSON出现NSCocoaErrorDomain Code=3840的解决方法

    最近在使用AFNetworkWorking读取JSON时,出现了NSCocoaErrorDomain Code=3840的错误.这种错误应该是服务器端返回JSON格式不对造成的.通过Google搜到这 ...

  5. linux -- nano

    今天在git commit的时候碰到了一种编辑方式 -- 不会用 T.T,然后找了下相关的文档. ^G -- ctrl+g 帮助文档 ^O -- ctrl+o 写出,会出现下面的一行提示,是否保存,直 ...

  6. 自己动手写Logistic回归算法

    假设一个数据集有n个样本,每个样本有m个特征,样本标签y为{0, 1}. 数据集可表示为: 其中,x(ij)为第i个样本的第j个特征值,y(i)为第i个样本的标签. X矩阵左侧的1相当于回归方程的常数 ...

  7. Bootstrap_缩略图

    缩略图在网站中最常用的地方就是产品列表页面,一行显示几张图片,有的在图片底下(左侧或右侧)带有标题.描述等信息. Bootstrap框架将这一部独立成一个模块组件.并通过“thumbnail”样式配合 ...

  8. DTP激活时报Overlapping

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  9. sql连表分页查询(存储过程)

    1.平时分页查询都比较多针对一个表的数据 而这个分页查询是针对连表查询的 ,这也是我网上改版别人的sql语句 先在数据库新建一个存储过程 拷贝以下代码 CREATE PROCEDURE [dbo].[ ...

  10. JS获取Url中传入的参数

    一:后台获取,前台调用 后台: object value= Request.QueryString[key]; 前台js: $(function(){ var value="<%=va ...