Shiro认证流程源码分析
subject.login() ——> DelegatingSubject.login() ——> DefaultSecurityManager.login() ——> AbstractAuthenticator的authenticate() ——> ModularRealmAuthentiscat的doAuthenticate() ——> AuthenticatingRealm的抽象方法doGetAuthenticationInfo() ——> 自定义Realm重写doGetAuthenticationInfo(需继承AuthorizingRealm,AuthorizingRealm继承自AuthenticatingRealm)进行认证
DelegatingSubject 源码如下:
public class DelegatingSubject implements Subject {
......
public void login(AuthenticationToken token) throws AuthenticationException {
this.clearRunAsIdentitiesInternal();
// 此处继续调用login() -> DefaultSecurityManager.login()
Subject subject = this.securityManager.login(this, token);
// ...略
}
DefaultSecurityManager 的 login() 源码如下:
public class DefaultSecurityManager extends SessionsSecurityManager {
......
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
//此处会继续调用AbstractAuthenticator的authenticate()方法
info = this.authenticate(token);
} catch (AuthenticationException var7) {
AuthenticationException ae = var7;
try {
this.onFailedLogin(token, ae, subject);
} catch (Exception var6) {
if (log.isInfoEnabled()) {
log.info("onFailedLogin method threw an exception. Logging and propagating original AuthenticationException.", var6);
}
}
throw var7;
}
Subject loggedIn = this.createSubject(token, info, subject);
this.onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
}
AbstractAuthenticator 的 authenticate
源码如下:
public abstract class AbstractAuthenticator implements Authenticator, LogoutAware {
......
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
if (token == null) {
throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
} else {
log.trace("Authentication attempt received for token [{}]", token);
AuthenticationInfo info;
try {
// 调用自己的抽象方法
info = this.doAuthenticate(token);
// ......略
return info;
}
}
protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken var1) throws AuthenticationException;
}
ModularRealmAuthentiscator 实现了 doAuthenticate
,源码如下:
public class ModularRealmAuthenticator extends AbstractAuthenticator {
......
//1.得到自己注册的Realm类
//2.判断Realm的个数,然后执行doSingleRealmAuthentication或者doMultiRealmAuthentication