最近项目中用到了Shiro框架,Realm是具体实现业务逻辑的类,那么Shiro是如何加载相应的Realm呢?
跟踪源码发现
在ModularRealmAuthenticator.doMultiRealmAuthentication()方法中
下面代码用来加载相应的Realm
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);
}
}
根据 realm.supports(token)方法来判断当前的令牌信息对应的Realm.
在 基类AuthenticatingRealm中
public boolean supports(AuthenticationToken token) {
return token != null && getAuthenticationTokenClass().isAssignableFrom(token.getClass());
}
也就是每个 Realm只要覆盖getAuthenticationTokenClass()方法来支持相应的Token类.
public Class getAuthenticationTokenClass() {
return authenticationTokenClass;
}