Apache Shiro 学习记录1
最近几天在学习Apache Shiro......看了一些大神们的教程.....感觉收获不少.....但是毕竟教程也只是指引一下方向....即使是精品教程,仍然有很多东西都没有说明....所以自己也稍微研究了一下...记录了一下我的研究发现....教程点这里
这篇教程的最后提到了strategy.....然后给出了4个方法.....但是并没有怎么详细说明.....我想说说我的理解.....(我的理解可能会有很多错误)
我想先说说登陆验证的大致流程....大致......
Subject
从用户那里收集完用户名密码以后我们会调用subject.login(token)这个方法去登陆.....Subject是一个接口,没有定义login的具体实现.....Shiro里只有一个类实现了这个接口,是DelegatingSubject这个类.这个类里的方法login方法如下:
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
Subject subject = securityManager.login(this, token); PrincipalCollection principals; String host = null; if (subject instanceof DelegatingSubject) {
DelegatingSubject delegating = (DelegatingSubject) subject;
//we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
principals = delegating.principals;
host = delegating.host;
} else {
principals = subject.getPrincipals();
} if (principals == null || principals.isEmpty()) {
String msg = "Principals returned from securityManager.login( token ) returned a null or " +
"empty value. This value must be non null and populated with one or more elements.";
throw new IllegalStateException(msg);
}
this.principals = principals;
this.authenticated = true;
if (token instanceof HostAuthenticationToken) {
host = ((HostAuthenticationToken) token).getHost();
}
if (host != null) {
this.host = host;
}
Session session = subject.getSession(false);
if (session != null) {
this.session = decorate(session);
} else {
this.session = null;
}
}
代码各种复杂=.= ..............我也看不懂....但是我看到第三行,明白了subject其实也是让securityManager来执行login操作的......那我们去看看securityManager吧......
SecurityManager
SecurityManager也是一个接口,各种继承,实现其他接口......还好实现类只有一个DefaultSecurityManager类...并且login方法直到这个类才被实现....
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = authenticate(token);
} catch (AuthenticationException ae) {
try {
onFailedLogin(token, ae, subject);
} catch (Exception e) {
if (log.isInfoEnabled()) {
log.info("onFailedLogin method threw an " +
"exception. Logging and propagating original AuthenticationException.", e);
}
}
throw ae; //propagate
} Subject loggedIn = createSubject(token, info, subject); onSuccessfulLogin(token, info, loggedIn); return loggedIn;
}
我觉得这里最重要的就是第四行的authenticate方法.......
这个方法是在DefaultSecurityManager的N层父类AuthenticatingSecurityManager里实现的....
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}
这里又可以看出SecurityManager的login方法其实也是委托给认证器authenticator调用authenticate(token)方法来实现的.
public abstract class AuthenticatingSecurityManager extends RealmSecurityManager { /**
* The internal <code>Authenticator</code> delegate instance that this SecurityManager instance will use
* to perform all authentication operations.
*/
private Authenticator authenticator; /**
* Default no-arg constructor that initializes its internal
* <code>authenticator</code> instance to a
* {@link org.apache.shiro.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator}.
*/
public AuthenticatingSecurityManager() {
super();
this.authenticator = new ModularRealmAuthenticator();
}
..................
}
认证器authenticator的默认实现是ModularRealmAuthenticator....this.authenticator = new ModularRealmAuthenticator();...所以我们再来看看ModularRealmAuthenticator..........
ModularRealmAuthenticator
ModularRealmAuthenticator的authenticate方法是继承自父类AbstractAuthenticator的..这个方法还是final的...
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { if (token == null) {
throw new IllegalArgumentException("Method argumet (authentication token) cannot be null.");
} log.trace("Authentication attempt received for token [{}]", token); AuthenticationInfo info;
try {
info = doAuthenticate(token);
if (info == null) {
String msg = "No account information found for authentication token [" + token + "] by this " +
"Authenticator instance. Please check that it is configured correctly.";
throw new AuthenticationException(msg);
}
} catch (Throwable t) {
AuthenticationException ae = null;
if (t instanceof AuthenticationException) {
ae = (AuthenticationException) t;
}
if (ae == null) {
//Exception thrown was not an expected AuthenticationException. Therefore it is probably a little more
//severe or unexpected. So, wrap in an AuthenticationException, log to warn, and propagate:
String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " +
"error? (Typical or expected login exceptions should extend from AuthenticationException).";
ae = new AuthenticationException(msg, t);
}
try {
notifyFailure(token, ae);
} catch (Throwable t2) {
if (log.isWarnEnabled()) {
String msg = "Unable to send notification for failed authentication attempt - listener error?. " +
"Please check your AuthenticationListener implementation(s). Logging sending exception " +
"and propagating original AuthenticationException instead...";
log.warn(msg, t2);
}
} throw ae;
} log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info); notifySuccess(token, info); return info;
}
从中我们可以看出比较重要的是第11行 info = doAuthenticate(token);
doAuthenticate(token)方法在ModularRealmAuthenticator之中被override过...
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
这里还是比较明显的,根据定义的Realm数量来决定是调用doSingleRealmAuthentication方法还是调用doMultiRealmAuthentication方法...
我们来看看doMultiRealmAuthentication方法里到底做了些什么呢..这个方法是定义在ModularRealmAuthenticator里的...
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) { AuthenticationStrategy strategy = getAuthenticationStrategy(); AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token); if (log.isTraceEnabled()) {
log.trace("Iterating through {} realms for PAM authentication", realms.size());
} for (Realm realm : realms) { aggregate = strategy.beforeAttempt(realm, token, aggregate); if (realm.supports(token)) { log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm); AuthenticationInfo info = null;
Throwable t = null;
try {
info = realm.getAuthenticationInfo(token);
} catch (Throwable throwable) {
t = throwable;
if (log.isDebugEnabled()) {
String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
log.debug(msg, t);
}
} aggregate = strategy.afterAttempt(realm, token, info, aggregate, t); } else {
log.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token);
}
} aggregate = strategy.afterAllAttempts(token, aggregate); return aggregate;
}
虽然很多看不明白....但是我大致流程能看懂:
在调用每个Realm之前,先执行strategy.beforeAllAttempts(realms, token);
然后再进入 for (Realm realm : realms),就是准备去调用每个realm来认证..不过每个Realm认证之前还要调用aggregate = strategy.beforeAttempt(realm, token, aggregate);
然后得到单个Realm的认证结果 info = realm.getAuthenticationInfo(token);
再调用aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);这里可能会把info的认证信息和aggregate合并,就是把principle合并....不过还是要看具体的strategy的.
最后再调用 aggregate = strategy.afterAllAttempts(token, aggregate);
也就是说strategy.beforeAllAttempts(realms, token);调用1次,然后根据realm的数量调用N次strategy.beforeAttempt(realm, token, aggregate);N次realm.getAuthenticationInfo(token);N次 strategy.afterAttempt(realm, token, info, aggregate, t);再调用1次strategy.afterAllAttempts(token, aggregate);
另外,不是说你单个Realm里认证失败,比如抛出了UnknownAccountException..所有认证就终止了....仔细看第23,24行会发现Realm里抛出的异常是会被拦截下来的...然后传给了 strategy.afterAttempt(realm, token, info, aggregate, t);....发现了这个异常以后到底是算认证失败了还是继续看其他的Realm是根据strategy来的...比如AllSuccessfulStrategy的afterAttempt方法...发现了任意1个realm抛出的异常,就直接抛出异常,终止认证....但是AtLeastOneSuccessfulStrategy就不一样...它就会无视这个异常...继续下面realm来认证...然后根据afterAllAttempts里的AuthenticationInfo的汇总信息来判断到底是认证失败了要抛出异常还是认证是成功的....
Shiro默认的策略是AtLeastOneSuccessfulStrategy
各种Strategy
我觉得看到这里我们可以再来看看Shiro已经定义的三种Strategy了...教程里提到过:
FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功的认证信息,其他的忽略;
AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份验证成功的认证信息;
AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
这3种策略都继承自AbstractAuthenticationStrategy类..这个抽象类里定义了前面提到的2个after方法和2个before方法还有1个merge方法...
protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
if( aggregate instanceof MergableAuthenticationInfo ) {
((MergableAuthenticationInfo)aggregate).merge(info);
return aggregate;
} else {
throw new IllegalArgumentException( "Attempt to merge authentication info from multiple realms, but aggregate " +
"AuthenticationInfo is not of type MergableAuthenticationInfo." );
}
}
merge方法会调用AuthenticationInfo的merge方法....大致过程是:
public void merge(AuthenticationInfo info) {
if (info == null || info.getPrincipals() == null || info.getPrincipals().isEmpty()) {
return;
} if (this.principals == null) {
this.principals = info.getPrincipals();
} else {
if (!(this.principals instanceof MutablePrincipalCollection)) {
this.principals = new SimplePrincipalCollection(this.principals);
}
((MutablePrincipalCollection) this.principals).addAll(info.getPrincipals());
}
......................
}
大致意思就是把info的principals合并到aggregate的principals上去....
AbstractAuthenticationStrategy的merge方法主要是在afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t)里被调用,因为经过一个Realm的认证以后会得到info对象...这个时候不同的认证策略就需要考虑是不是要把当前得到的info合并到已经有的前面几个Realm积累下来的aggregateInfo里去了...
举例:
AllSuccessfulStrategy类
public AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
if (!realm.supports(token)) {
String msg = "Realm [" + realm + "] of type [" + realm.getClass().getName() + "] does not support " +
" the submitted AuthenticationToken [" + token + "]. The [" + getClass().getName() +
"] implementation requires all configured realm(s) to support and be able to process the submitted " +
"AuthenticationToken.";
throw new UnsupportedTokenException(msg);
} return info;
}
第2行,如果realm不支持token,显然这个realm是认证失败的...而AllSuccessfulStrategy策略需要所有Realm都认证成功才行...果断抛出异常...
public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo info, AuthenticationInfo aggregate, Throwable t)
throws AuthenticationException {
if (t != null) {
if (t instanceof AuthenticationException) {
//propagate:
throw ((AuthenticationException) t);
} else {
String msg = "Unable to acquire account data from realm [" + realm + "]. The [" +
getClass().getName() + " implementation requires all configured realm(s) to operate successfully " +
"for a successful authentication.";
throw new AuthenticationException(msg, t);
}
}
if (info == null) {
String msg = "Realm [" + realm + "] could not find any associated account data for the submitted " +
"AuthenticationToken [" + token + "]. The [" + getClass().getName() + "] implementation requires " +
"all configured realm(s) to acquire valid account data for a submitted token during the " +
"log-in process.";
throw new UnknownAccountException(msg);
} log.debug("Account successfully authenticated using realm [{}]", realm); // If non-null account is returned, then the realm was able to authenticate the
// user - so merge the account with any accumulated before:
merge(info, aggregate); return aggregate;
}
Throwable t, t是从Realm里抛出来的,如果Realm抛出了异常,不管什么原因,认证肯定是失败了...所以Strategy也要抛出异常,即认证失败了......info = null的道理也是一样的....
AtLeastOneSuccessfulStrategy类:
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
//we know if one or more were able to succesfully authenticate if the aggregated account object does not
//contain null or empty data:
if (aggregate == null || CollectionUtils.isEmpty(aggregate.getPrincipals())) {
throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
"could not be authenticated by any configured realms. Please ensure that at least one realm can " +
"authenticate these tokens.");
} return aggregate;
}
所有Realm的认证都执行完毕之后,如果AuthenticationInfo 的合并结果aggregate还是null或者空的话那么说明所有Realm的认证都失败的...那么就应该抛出异常,说明认证失败了....
FirstSuccessfulStrategy类:
public class FirstSuccessfulStrategy extends AbstractAuthenticationStrategy { /**
* Returns {@code null} immediately, relying on this class's {@link #merge merge} implementation to return
* only the first {@code info} object it encounters, ignoring all subsequent ones.
*/
public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
return null;
} /**
* Returns the specified {@code aggregate} instance if is non null and valid (that is, has principals and they are
* not empty) immediately, or, if it is null or not valid, the {@code info} argument is returned instead.
* <p/>
* This logic ensures that the first valid info encountered is the one retained and all subsequent ones are ignored,
* since this strategy mandates that only the info from the first successfully authenticated realm be used.
*/
protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
return aggregate;
}
return info != null ? info : aggregate;
}
}
为什么要override beforeAllAttempts方法返回null我也不懂....父类是返回new SimpleAuthenticationInfo();.....
override merge方法是因为FirstSuccessfulStrategy策略只返回第一个验证成功的Realm的AuthenticationInfo ...
如果aggregate不是空的或者null,说明前面的Realm有成功过,那么根据策略,这个时候不应该把本次realm得到的info合并进去.....而是直接返回前面验证成功的AuthenticationInfo ......
Apache Shiro 学习记录1的更多相关文章
- Apache Shiro 学习记录5
本来这篇文章是想写从Factory加载ini配置到生成securityManager的过程的....但是貌似涉及的东西有点多...我学的又比较慢...很多类都来不及研究,我又怕等我后面的研究了前面的都 ...
- Apache Shiro 学习记录4
今天看了教程的第三章...是关于授权的......和以前一样.....自己也研究了下....我觉得看那篇教程怎么说呢.....总体上是为数不多的精品教程了吧....但是有些地方确实是讲的太少了.... ...
- Apache Shiro 学习记录2
写完上篇随笔以后(链接).....我也想自己尝试一下写一个Strategy.....Shiro自带了3个Strategy,教程(链接)里作者也给了2个.....我想写个都不一样的策略.....看来看去 ...
- Apache Shiro 学习记录3
晚上看了教程的第三章....感觉Shiro字符串权限很好用....但是教程举的例子太少了.....而且有些地方讲的不是很清楚....所以我也自己测试了一下....记录一下测试的结果.... (1) * ...
- Apache Shiro学习-2-Apache Shiro Web Support
Apache Shiro Web Support 1. 配置 将 Shiro 整合到 Web 应用中的最简单方式是在 web.xml 的 Servlet ContextListener 和 Fil ...
- apache shiro学习笔记
一.权限概述 1.1 认证与授权 认证:系统提供的用于识别用户身份的功能,通常登录功能就是认证功能-----让系统知道你是谁?? 授权:系统授予用户可以访问哪些功能的许可(证书)----让系统知道你能 ...
- Apache shiro学习总结
Apache shiro集群实现 (一) shiro入门介绍 Apache shiro集群实现 (二) shiro 的INI配置 Apache shiro集群实现 (三)shiro身份认证(Shiro ...
- Java安全框架 Apache Shiro学习-1-ini 配置
简单登录流程: 1. SecurityManager 2. SecurityUtils.setSecurityManager 3. SecurityUtils.getSubject ...
- shiro学习记录(三)
1.使用ehcache缓存权限数据 ehcache是专门缓存插件,可以缓存Java对象,提高系统性能. l ehcache提供的jar包: 第一步:在pom.xml文件中引入ehcache的依赖 &l ...
随机推荐
- android 学习JSON
JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...
- Service 广播 到Fragment
//Fragment public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Sys ...
- -bash: /bin/rm: Argument list too long
使用rm * -f删除缓存目录文件时,报如下错误 -bash: /bin/rm: Argument list too long 提示文件数目太多. 解决的办法是使用如下命令: ls | xargs - ...
- 一张图看懂ANSYS17.0 流体 新功能与改进
一张图看懂ANSYS17.0 流体 新功能与改进 提交 我的留言 加载中 已留言 一张图看懂ANSYS17.0 流体 新功能与改进 原创2016-02-03ANSYS模拟在线模拟在线 模拟在线 ...
- ThreadLocal
package cn.happy.util; import org.hibernate.Session;import org.hibernate.SessionFactory;import org.h ...
- PAT 1035. 插入与归并(25)
根据维基百科的定义: 插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列.每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置.如此迭代直到全部元素有序. 归并排序进行如下迭 ...
- 安装win7x64、x86总提示文件出错或安装大型软件出错或0x0000001a、0x0000003b蓝屏
从不同地方下载好几个安装包,安装时候到展开文件步骤总是提示文件出错,无法安装下去. 这样可以确认不会是安装包出问题. 搜索原因,偶然看到可能与内存有关. 就检测了一遍,过程:控制面板>管理工具& ...
- Apache Shiro系列四,概述 —— Shiro的架构
Shiro的设计目标就是让应用程序的安全管理更简单.更直观. 软件系统一般是基于用户故事来做设计.也就是我们会基于一个客户如何与这个软件系统交互来设计用户界面和服务接口.比如,你可能会说:“如 ...
- scalatest的userguide
http://www.scalatest.org/user_guide 感觉功能很强大.这门语言有前途.
- 基于SuperSocket的IIS主动推送消息给android客户端
在上一篇文章<基于mina框架的GPS设备与服务器之间的交互>中,提到之前一直使用superwebsocket框架做为IIS和APP通信的媒介,经常出现无法通信的问题,必须一天几次的手动回 ...