登录流程分析
这里我们要来解决两个问题
1. 如何获取当前用户
2. 当前用户怎么登录成功的
@Test
public void testLogin(){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
usernamePasswordToken.setUsername("root");
usernamePasswordToken.setPassword("secret".toCharArray());
subject.login(usernamePasswordToken);
Assert.assertTrue("验证失败",subject.isAuthenticated());
}
获取Subject (一)
SecurityUtils.getSubject()
获得ThreadLocal 缓存中是不是有Subject,
没有就去创建一个
public static Subject getSubject() {
// 获得ThreadLocal 变量Map<String,Object> 中key为 org.apache.shiro.util.ThreadContext_SUBJECT_KEY 的值
// 第一次获取为null
Subject subject = ThreadContext.getSubject();
if (subject == null) {
subject = (new Subject.Builder()).buildSubject();
// 设置ThreadLocal 变量Map<String,Object> 中key为 org.apache.shiro.util.ThreadContext_SUBJECT_KEY 的值为 subject
ThreadContext.bind(subject);
}
return subject;
}
级别3-1
subject = (new Subject.Builder()).buildSubject();
初始化Builder
设置Builder的securityManager,subjectContext
“`
public Builder() {
this(SecurityUtils.getSecurityManager());
}
public Builder(SecurityManager securityManager) {
if (securityManager == null) {
throw new NullPointerException("SecurityManager method argument cannot be null.");
}
this.securityManager = securityManager;
// 新建subjectContext 实例 new DefaultSubjectContext();
this.subjectContext = newSubjectContextInstance();
if (this.subjectContext == null) {
throw new IllegalStateException("Subject instance returned from 'newSubjectContextInstance' " +
"cannot be null.");
}
this.subjectContext.setSecurityManager(securityManager);
}
“`
级别3-2
subject = (new Subject.Builder()).buildSubject();
委托给 securityManager 创建
public Subject buildSubject() {
return this.securityManager.createSubject(this.subjectContext);
}
## 创建Subject
级别4
return this.securityManager.createSubject(this.subjectContext);
通过subjectContext 创建subject
DefaultSecurityManager
public Subject createSubject(SubjectContext subjectContext) {
//create a copy so we don't modify the argument's backing map:
// 新建一个backingMap 副本的 SubjectContext
SubjectContext context = copy(subjectContext);
//ensure that the context has a SecurityManager instance, and if not, add one:
// context 的backingMap中获取key为org.apache.shiro.subject.support.DefaultSubjectContext.SECURITY_MANAGER 的subject
// 如果获取不到就设置为this
context = ensureSecurityManager(context);
//Resolve an associated Session (usually based on a referenced session ID), and place it in the context before
//sending to the SubjectFactory. The SubjectFactory should not need to know how to acquire sessions as the
//process is often environment specific - better to shield the SF from these details:
context = resolveSession(context);
//Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first
//if possible before handing off to the SubjectFactory:
context = resolvePrincipals(context);
return getSubjectFactory().createSubject(context);
}
### 创建Subject(一)
级别5-1
“`
protected SubjectContext resolveSession(SubjectContext context) {
if (context.resolveSession() != null) {
log.debug(“Context already contains a session. Returning.”);
return context;
}
try {
//Context couldn’t resolve it directly, let’s see if we can since we have direct access to
//the session manager:
//
Session session = resolveContextSession(context);
if (session != null) {
context.setSession(session);
}
} catch (InvalidSessionException e) {
log.debug(“Resolved SubjectContext context session is invalid. Ignoring and creating an anonymous ” +
“(session-less) Subject instance.”, e);
}
return context;
}
“`
级别6-1
context.resolveSession()
- 从backingMap中获取session
从bexistingSubject中获取session
如果都没获取到就返回nullpublic Session resolveSession() { Session session = getSession(); if (session == null) { //try the Subject if it exists: Subject existingSubject = getSubject(); if (existingSubject != null) { session = existingSubject.getSession(false); } } return session; }
级别6-2
当 context.getSessionId() 不为null,就创建一个Session
protected Session resolveContextSession(SubjectContext context) throws InvalidSessionException {
SessionKey key = getSessionKey(context);
if (key != null) {
return getSession(key);
}
return null;
}
创建Subject(二)
Principals 获取顺序
级别5-2
protected SubjectContext resolvePrincipals(SubjectContext context) {
// 从上下文中获取责任人
PrincipalCollection principals = context.resolvePrincipals();
if (CollectionUtils.isEmpty(principals)) {
log.trace("No identity (PrincipalCollection) found in the context. Looking for a remembered identity.");
// 从RememberMe 中获取责任人
principals = getRememberedIdentity(context);
if (!CollectionUtils.isEmpty(principals)) {
log.debug("Found remembered PrincipalCollection. Adding to the context to be used " +
"for subject construction by the SubjectFactory.");
context.setPrincipals(principals);
bindPrincipalsToSession(principals, context);
} else {
log.trace("No remembered identity found. Returning original context.");
}
}
return context;
}
级别6-1
context.resolvePrincipals();
- 从backingMap 中获取 Principals
- 从backingMap 中获取 AuthenticationInfo 对象,不为空就获取Principals
- 从backingMap 中获取 Subject 对象,不为空就获取Principals
- 从backingMap 中获取 Session 对象,不为空就获取Principals
public PrincipalCollection resolvePrincipals() {
PrincipalCollection principals = getPrincipals();
if (CollectionUtils.isEmpty(principals)) {
//check to see if they were just authenticated:
AuthenticationInfo info = getAuthenticationInfo();
if (info != null) {
principals = info.getPrincipals();
}
}
if (CollectionUtils.isEmpty(principals)) {
Subject subject = getSubject();
if (subject != null) {
principals = subject.getPrincipals();
}
}
if (CollectionUtils.isEmpty(principals)) {
//try the session:
Session session = resolveSession();
if (session != null) {
principals = (PrincipalCollection) session.getAttribute(PRINCIPALS_SESSION_KEY);
}
}
return principals;
}
创建Subject(三)
级别5-3
通过上下文的属性去创建 DelegatingSubject
return getSubjectFactory().createSubject(context);
public Subject createSubject(SubjectContext context) {
SecurityManager securityManager = context.resolveSecurityManager();
Session session = context.resolveSession();
PrincipalCollection principals = context.resolvePrincipals();
boolean authenticated = context.resolveAuthenticated();
String host = context.resolveHost();
return newSubjectInstance(principals, authenticated, host, session, securityManager);
}
protected Subject newSubjectInstance(PrincipalCollection principals, boolean authenticated, String host,
Session session, SecurityManager securityManager) {
return new DelegatingSubject(principals, authenticated, host, session, securityManager);
}
到这里就已经创建了Subject 的实现类DelegatingSubject 的实例,进行返回了。
最后在级别2中设置 ThreadContext.bind(subject);
当再次进行 SecurityUtils.getSubject(); 获取的时候,就会从ThreadLocal 变量中获取Subject实例了
当前用户怎么登录成功的
subject.login(usernamePasswordToken);
级别1
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentities();
// 委托给 securityManager 执行login
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);
this.runAsPrincipals = getRunAsPrincipals(this.session);
} else {
this.session = null;
}
// 更新subject
ThreadContext.bind(this);
}
级别2-1
Subject subject = securityManager.login(this, token);
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);
bind(loggedIn);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
级别3-1
info = authenticate(token);
委托给this.authenticator 进行验证
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}
级别4
return this.authenticator.authenticate(token);
AbstractAuthenticator::authenticate
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;
}
```
**级别5-1**
> info = doAuthenticate(token);
AbstractAuthenticator 类中定义
```
protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token)
throws AuthenticationException;
```
由子类实现
具体实现类ModularRealmAuthenticator 实现了 doAuthenticate
```
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
// 验证是不是为空, 必须至少要存在一个 Realm 的实现
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
// 单个验证, 当前是 ini 的实现,所以只有一个Realm
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
// 多个验证器时,可以选择验证策略
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
```
**级别6**
再来回忆一遍IniRealm类图
![IniRealm 类图](https://gitee.com/ls9527/src-analysis/raw/master/shiro/uml/IniRealm.png)
```
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
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);
}
// 注册的IniRealm 去获得认证信息
AuthenticationInfo info = realm.getAuthenticationInfo(token);
if (info == null) {
String msg = "Realm [" + realm + "] was unable to find account data for the " +
"submitted AuthenticationToken [" + token + "].";
throw new UnknownAccountException(msg);
}
return info;
}
```
**级别7-1**
>realm.supports(token)
是否支持token类型, 默认支持 UsernamePasswordToken 类型
```
private Class<? extends AuthenticationToken> authenticationTokenClass = UsernamePasswordToken.class;
public Class getAuthenticationTokenClass() {
return authenticationTokenClass;
}
public boolean supports(AuthenticationToken token) {
return token != null && getAuthenticationTokenClass().isAssignableFrom(token.getClass());
}
```
**级别7-2**
> AuthenticationInfo info = realm.getAuthenticationInfo(token);
1. 根据token获取 AuthenticationInfo
2. 判断 AuthenticationToken 和 AuthenticationInfo 的 Credentials(凭证) 是否相等
凭证不匹配就抛出异常
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info = doGetAuthenticationInfo(token);
if (info == null) {
if (log.isDebugEnabled()) {
String msg = "No authentication information found for submitted authentication token [" + token + "]. " +
"Returning null.";
log.debug(msg);
}
return null;
}
CredentialsMatcher cm = getCredentialsMatcher();
if (cm != null) {
// 判断凭证是否相等
if (!cm.doCredentialsMatch(token, info)) {
String msg = "The credentials provided for account [" + token +
"] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
"credentials during authentication. If you do not wish for credentials to be examined, you " +
"can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
}
return info;
}
**级别8-1**
> AuthenticationInfo info = doGetAuthenticationInfo(token);
当前方法: SimpleAccountRealm::doGetAuthenticationInfo
返回用户的认证信息 SimpleAccount(**SimpleAccount 实现了AuthenticationInfo 接口**)
// 这里是加载SecurityManager 的时候初始化的
protected final Map
**级别8-2**
> 级别7-2: cm.doCredentialsMatch(token, info)
判断两个Credentials 是否相等
(UsernamePasswordToken的 getCredentials() 会返回password )
SimpleCredentialsMatcher
protected boolean equals(Object tokenCredentials, Object accountCredentials) {
if (log.isDebugEnabled()) {
log.debug("Performing credentials equality check for tokenCredentials of type [" +
tokenCredentials.getClass().getName() + " and accountCredentials of type [" +
accountCredentials.getClass().getName() + "]");
}
if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
if (log.isDebugEnabled()) {
log.debug("Both credentials arguments can be easily converted to byte arrays. Performing " +
"array equals comparison");
}
byte[] tokenBytes = toBytes(tokenCredentials);
byte[] accountBytes = toBytes(accountCredentials);
return Arrays.equals(tokenBytes, accountBytes);
} else {
return accountCredentials.equals(tokenCredentials);
}
}
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
Object tokenCredentials = getCredentials(token);
Object accountCredentials = getCredentials(info);
return equals(tokenCredentials, accountCredentials);
}
UsernamePasswordToken
public Object getCredentials() {
return getPassword();
}
**级别5-2**
> notifySuccess(token, info);
成功后依次通知 AuthenticationListener 监听器
AbstractAuthenticator
protected void notifySuccess(AuthenticationToken token, AuthenticationInfo info) {
for (AuthenticationListener listener : this.listeners) {
listener.onSuccess(token, info);
}
}
**级别3-2**
> Subject loggedIn = createSubject(token, info, subject);
protected SubjectContext createSubjectContext() {
return new DefaultSubjectContext();
}
protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
SubjectContext context = createSubjectContext();
context.setAuthenticated(true);
context.setAuthenticationToken(token);
context.setAuthenticationInfo(info);
if (existing != null) {
context.setSubject(existing);
}
return createSubject(context);
}
**级别4-1**
> createSubject
一段十分熟悉的代码段。
根据subjectContext 创建一个DelegatingSubject
这一步主要就是根据token,info 复制一个 带凭证信息的 subject
subject是没有登录的subject. 根据token info 创建一个新的subject
DefaultSecurityManager
public Subject createSubject(SubjectContext subjectContext) {
//create a copy so we don't modify the argument's backing map:
SubjectContext context = copy(subjectContext);
//ensure that the context has a SecurityManager instance, and if not, add one:
context = ensureSecurityManager(context);
//Resolve an associated Session (usually based on a referenced session ID), and place it in the context before
//sending to the SubjectFactory. The SubjectFactory should not need to know how to acquire sessions as the
//process is often environment specific - better to shield the SF from these details:
context = resolveSession(context);
//Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first
//if possible before handing off to the SubjectFactory:
context = resolvePrincipals(context);
return getSubjectFactory().createSubject(context);
}
**级别3-3**
> bind(loggedIn);
1. 获得凭证信息 PrincipalCollection
2. 获得session, 如果不存在就创建一个session (session 源码分析放后面)
3. 判断是否验证通过 认证通过就设置session的key: AUTHENTICATED_SESSION_KEY 为true,
认证失败就移除session的key: AUTHENTICATED_SESSION_KEY
DefaultSecurityManager
protected void bind(Subject subject) {
// TODO consider refactoring to use Subject.Binder.
// This implementation was copied from SessionSubjectBinder that was removed
PrincipalCollection principals = subject.getPrincipals();
if (principals != null && !principals.isEmpty()) {
Session session = subject.getSession();
bindPrincipalsToSession(principals, session);
} else {
Session session = subject.getSession(false);
if (session != null) {
session.removeAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
}
}
if (subject.isAuthenticated()) {
Session session = subject.getSession();
session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, subject.isAuthenticated());
} else {
Session session = subject.getSession(false);
if (session != null) {
session.removeAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
}
}
}
**级别4-1**
> bindPrincipalsToSession(principals, session);
都不为空的情况下,设置session的key: PRINCIPALS_SESSION_KEY
private void bindPrincipalsToSession(PrincipalCollection principals, Session session) throws IllegalArgumentException {
if (session == null) {
throw new IllegalArgumentException(“Session argument cannot be null.”);
}
if (CollectionUtils.isEmpty(principals)) {
throw new IllegalArgumentException(“Principals cannot be null or empty.”);
}
session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, principals);
}
**级别3-4**
> onSuccessfulLogin(token, info, loggedIn);
RememberMeManager 管理器不为null时,就保存用户信息
protected void rememberMeSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info, Subject subject) {
RememberMeManager rmm = getRememberMeManager();
if (rmm != null) {
try {
rmm.onSuccessfulLogin(subject, token, info);
} catch (Exception e) {
if (log.isWarnEnabled()) {
String msg = “Delegate RememberMeManager instance of type [” + rmm.getClass().getName() +
“] threw an exception during onSuccessfulLogin. RememberMe services will not be ” +
“performed for account [” + info + “].”;
log.warn(msg, e);
}
}
} else {
if (log.isTraceEnabled()) {
log.trace(“This ” + getClass().getName() + ” instance does not have a ” +
“[” + RememberMeManager.class.getName() + “] instance configured. RememberMe services ” +
“will not be performed for account [” + info + “].”);
}
}
}
protected void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info, Subject subject) {
rememberMeSuccessfulLogin(token, info, subject);
}
**级别2-2**
> this.session = decorate(session);
关联 session 和 DelegatingSubject,当session失效时,清理subject的session
private class StoppingAwareProxiedSession extends ProxiedSession {
private final DelegatingSubject owner;
private StoppingAwareProxiedSession(Session target, DelegatingSubject owningSubject) {
super(target);
owner = owningSubject;
}
public void stop() throws InvalidSessionException {
super.stop();
owner.sessionStopped();
}
}
protected Session decorate(Session session) {
if (session == null) {
throw new IllegalArgumentException(“session cannot be null”);
}
return new StoppingAwareProxiedSession(session, this);
}
“`
级别2-3
ThreadContext.bind(this);
更新 subject