shiro认证代码流程

认证流程

  1. subject提交认证,传过去token参数
  2. DelegatingSubject代理类调用securityManager.login(this,token),此方法会通过token查询,获取到一个subject,接下来会对这个subject进行检查,如果没有问题,就把subject的内容塞入到this中,也就是当前调用认证方法的那个subject中,完成副作用。
  3. DefaultSecurityManager的login方法拿到subject和token参数后,调用父类的方法:authenticate(token)来获取到一个认证信息AuthenticationInfo。接下来会调用createSubject方法,把AuthenticationInfo、token和subject重新组装成一个新的subject,返回。
  4. AuthenticatingSecurityManager方法中的authenticate(token)方法接收到token后,执行操作,return this.authenticator.authenticate(token)。authenticator在new的时候就自动创建完成,为ModularAuthenticator,返回一个认证信息AuthenticationInfo。
  5. AbstractAuthenticator方法中会有一个方法info = doAuthenticate(token),来获取认证信息,ModularAuthenticator方法中写了这个。
  6. ModularAuthenticator方法继承了抽象类AbstractAuthenticator,拿到token后去realm里查询用户的认证信息,自定义的realm就在这里的集合中,通过注入的方式加入集合,也可以配置认证的三个策略。自定义的realm覆盖重写doGetAuthenticationInfo方法。

subject.login(token)

1
2
3
4
5
6
7
// 执行认证的提交
try {
subject.login(token);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

DelegatingSubject

subject的代理类。

1
2
3
public class DelegatingSubject implements Subject {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
// subject是返回的已经认证处理过的,根据token去查询出来的subject对象
Subject subject = securityManager.login(this, token);
// 用户的身份凭证信息
PrincipalCollection principals;
String host = null;
// 把subject中获取到的凭证信息放进去
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);
}
// 有合法的凭证信息,就全部塞到调用login的那个subject中,完成副作用
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;
}
}

DefaultSecurityManager

这是一个默认的安全管理器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
// 根据token去进行认证,返回一个认证信息,authenticationInfo
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,返回这个已经通过认证的,已登录的subject
Subject loggedIn = createSubject(token, info, subject);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}

AuthenticatingSecurityManager

1
2
3
4
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
// 值得一提的是这个authenticator是默认的new的一个ModularRealmAuthenticator
return this.authenticator.authenticate(token);
}

AbstractAuthenticator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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中,否则抛异常
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;
}

ModularRealmAuthenticator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
// 判断多个realm还是单个realm
if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
// 单个realm进行认证
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);
}
// 这个get方法就是我们自定义realm的时候override的方法
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;
}

注意的是,ModularRealmAuthenticator中的realm,是有set方法的,在spring中直接通过配置文件注入的方式set进来即可。

多个realm的配置方法

其中也有三种不同的realm认证策略,基本上都是针对多个realm配置的情况。

1
2
3
4
5
6
// 配置认证策略
DefaultSecurityManager securityManager = new DefaultSecurityManager();
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
authenticator.setAuthenticationStrategy(new AllSuccessfulStrategy());
securityManager.setAuthenticator(authenticator);

ini配置方法

1
2
3
4
5
6
[main]
#authenticator
authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
authenticationStrategy=org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy
authenticator.authenticationStrategy=$authenticationStrategy
securityManager.authenticator=$authenticator

spring注入的方法

1
2
3
4
<!-- 配置认证策略 -->
<property name="authenticator.authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy" />
</property>