接前文,在拿到
Subject
实例之后,我们经常调用的就是其login
和logout
方法了。本文就让我们好好看看这两个方法,让心理有个谱。再次强调,本人阅读的Shiro版本为1.3.2。
1. 前言
我们拿到的Subject
实例,在web环境下的其实际类型是WebDelegatingSubject
。而WebDelegatingSubject
的基类正是DelegatingSubject
;并且对于login
和logout
方法,WebDelegatingSubject
并没有进行覆写操作。
2. DelegatingSubject.login
方法
WebDelegatingSubject
并没有覆写基类DelegatingSubject
的login
方法。
注意方法subject.login(token)
上是有check exception的,其类型为AuthenticationException
;我们可以看看这个AuthenticationException
的相关子类,会发现一大堆非常熟悉的校验相关的异常。
// DelegatingSubject.login
public void login(AuthenticationToken token) throws AuthenticationException {
// 从Session中移除指定Key。
clearRunAsIdentitiesInternal();
// 原来除了构建Subject实例,登录操作也是委托给了securityManager。
// 这里的securityManager实际类型为DefaultWebSecurityManager; 而logout方法的实现是在其基类DefaultSecurityManager中定义的。
// 本次关注的重点
Subject subject = securityManager.login(this, token);
// 以下的操作就是将上面获取的subject实例中的属性复制给自身(即this)相对应的属性。
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;
}
}
3. DelegatingSubject.logout
方法
同样的,WebDelegatingSubject
并没有覆写基类DelegatingSubject
的logout
方法。
// DelegatingSubject.logout
public void logout() {
try {
clearRunAsIdentitiesInternal();
// 登出操作同样也是委托给了securityManager。
// 这里的securityManager实际类型为DefaultWebSecurityManager; 而logout方法的实现是在其基类DefaultSecurityManager中。
// 所以我们关注的重心还是DefaultSecurityManager
this.securityManager.logout(this);
} finally {
// 将自身相关的属性置空。
this.session = null;
this.principals = null;
this.authenticated = false;
//Don't set securityManager to null here - the Subject can still be
//used, it is just considered anonymous at this point. The SecurityManager instance is
//necessary if the subject would log in again or acquire a new session. This is in response to
//https://issues.apache.org/jira/browse/JSEC-22
//this.securityManager = null;
}
}
4. DefaultSecurityManager
类
按照上面的跟踪,这才是我们的目的地。登录登出的操作都是委托给了本类,让我们来看看具体的实现逻辑。
4.1 DefaultSecurityManager.login
类
// DefaultSecurityManager.login ; 登录
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
// 重点,下文讲解。
// 定义在基类AuthenticatingSecurityManager中。
// 我们自定义的Realm里进行鉴权时返回的就是这个info
info = authenticate(token);
} catch (AuthenticationException ae) {
try {
// 回调RememberMeManager接口实现类的onFailedLogin方法
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);
// 回调RememberMeManager接口实现类的onSuccessfulLogin方法
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
4.1.1 AbstractAuthenticator. authenticate
方法
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
// 非常简单的一句代码,就是将这个功能委派给了专门的Authenticator接口实现类去完成。
// 抽象类AbstractAuthenticator实现了这个方法。
// 我们平时所持有的实例一般都是其子类ModularRealmAuthenticator。
return this.authenticator.authenticate(token);
}
4.1.2 AbstractAuthenticator.authenticate
方法
// 为了节省篇幅,进行了一番裁剪。
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
// 抽象方法,交由子类去实现。
// 这里的子类是ModularRealmAuthenticator。
// 我们马上就要到了。
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;
}
try {
// 回调所有注册的AuthenticationListener接口实现类的onFailure方法
notifyFailure(token, ae);
} catch (Throwable t2) {
}
throw ae;
}
// 回调所有注册的AuthenticationListener接口实现类的onSuccess方法
notifySuccess(token, info);
return info;
}
4.1.3 ModularRealmAuthenticator.doAuthenticate
方法
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
// 确保存在Realm,一般由用户自定义实现。
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
// 只有一个Realm时
// 为简单起见,这次我们讲解这个。
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
// 多个Realm时
// 这里面用到了一个技巧就是:设计模式之——策略模式。
// 通过AuthenticationStrategy接口实现类,来选择
// 1. AllSuccessfulStrategy
// 2. AtLeastOneSuccessfulStrategy
// 3. FirstSuccessfulStrategy
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
4.1.4 ModularRealmAuthenticator.doSingleRealmAuthentication
方法
// ModularRealmAuthenticator.doSingleRealmAuthentication
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
// 所以我们自定义的Realm可以通过覆写该supports方法来决定自身支持的Token,
// 或者设置自身authenticationTokenClass字段的值也是可以的(基类AuthenticatingRealm实现的supports方法里的逻辑)
if (!realm.supports(token)) {
String msg = "Realm [" + realm + "] does not support authentication token [" +
token + "]. Please ensure that the appropriate Realm implementation is " +
"configured correctly or that the realm accepts AuthenticationTokens of this type.";
throw new UnsupportedTokenException(msg);
}
// 这个getAuthenticationInfo方法的实现是在AuthenticatingRealm类中,这个类也是我们自定义Realm时通常会选择继承的类
AuthenticationInfo info = realm.getAuthenticationInfo(token);
// 如果我们在自定义Realm中返回null, 就会抛出异常。
if (info == null) {
String msg = "Realm [" + realm + "] was unable to find account data for the " +
"submitted AuthenticationToken [" + token + "].";
throw new UnknownAccountException(msg);
}
return info;
}
4.1.5 AuthenticatingRealm.getAuthenticationInfo
方法
// AuthenticatingRealm抽象类也是我们实现自定义Realm时通常会选择继承的类。
// AuthenticatingRealm.getAuthenticationInfo
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 先尝试从缓存中获取, Shiro对Cache做了一层封装
AuthenticationInfo info = getCachedAuthenticationInfo(token);
if (info == null) {
//otherwise not cached, perform the lookup:
// 终于看到了回调我们自定义实现的位置了
// 如果在缓存中没有找到鉴权信息,则回调用户的实现来获取鉴权信息。
info = doGetAuthenticationInfo(token);
log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
if (token != null && info != null) {
cacheAuthenticationInfoIfPossible(token, info);
}
} else {
log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
}
// 这里也说明了:
// 如果我们想要实现类似 "密码错误五次短时间之类不允许再次登录"的效果的话,那在我们的自定义实现中,就一定要返回info
if (info != null) {
// 用户在使用Shiro鉴权前需要构建 token
// 而在自定义的Realm的鉴权逻辑里又需要返回 info
// 这里Shiro会将这两者进行比对, 确保用户正确输入
assertCredentialsMatch(token, info);
} else {
log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
}
return info;
}
4.2 DefaultSecurityManager.logout
类
// 登出
public void logout(Subject subject) {
if (subject == null) {
throw new IllegalArgumentException("Subject method argument cannot be null.");
}
// 拦截性接口;
// 默认实现是处理rememberMe功能; 委派给了专门的RememberMeManager接口去处理。
beforeLogout(subject);
PrincipalCollection principals = subject.getPrincipals();
if (principals != null && !principals.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Logging out subject with primary principal {}", principals.getPrimaryPrincipal());
}
// 实际类型为ModularRealmAuthenticator
Authenticator authc = getAuthenticator();
// ModularRealmAuthenticator实现了LogoutAware接口的
if (authc instanceof LogoutAware) {
// 下面讲解
((LogoutAware) authc).onLogout(principals);
}
}
try {
// 删除; 调用专门的subjectDAO接口实现类的delete方法
delete(subject);
} catch (Exception e) {
if (log.isDebugEnabled()) {
String msg = "Unable to cleanly unbind Subject. Ignoring (logging out).";
log.debug(msg, e);
}
} finally {
try {
// 停止session; 调用Shiro自身定义的Session接口的stop方法
stopSession(subject);
} catch (Exception e) {
if (log.isDebugEnabled()) {
String msg = "Unable to cleanly stop Session for Subject [" + subject.getPrincipal() + "] " +
"Ignoring (logging out).";
log.debug(msg, e);
}
}
}
}
4.2.1 ModularRealmAuthenticator.onLogout
方法
public void onLogout(PrincipalCollection principals) {
/*
进行事件通知,回调AuthenticationListener实现类的onLogout方法
*/
super.onLogout(principals);
// 查找所有注册了的Realm实现类
Collection<Realm> realms = getRealms();
if (!CollectionUtils.isEmpty(realms)) {
for (Realm realm : realms) {
// 我们自定义的Realm一般都是继承自AuthorizingRealm
// 而AuthorizingRealm间接实现了LogoutAware接口
// 所以对于登出时的自定义操作. 我们可以选择在自定义Realm中通过覆写onLogout来完成。
if (realm instanceof LogoutAware) {
((LogoutAware) realm).onLogout(principals);
}
}
}
}
5. 总结
Shiro留出的扩展点非常多,这里尝试总结下常用的。
1. AuthenticationListener
接口。
2. LogoutAware
接口。