本文以循序渐进的方式解析Shiro整个login过程的处理,读者可以边阅读本文边自己看代码来思考体会,如有问题,欢迎评论区探讨!

笔者shiro的demo源码路径:https://github.com/roostinghawk/ShiroDemo.git

1. 入口:Suject.login (比如Spring一般为LoginController)

    @PostMapping("/login")
public String login(@RequestParam("loginName") String loginName, @RequestParam("password") String password, Model model){
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginName, password);
Subject subject = SecurityUtils.getSubject(); try {
subject.login(usernamePasswordToken); // 入口
}catch (IncorrectCredentialsException ice){
model.addAttribute("login","password error");
return "error";
}catch (UnknownAccountException uae) {
model.addAttribute("login","userName error");
return "error";
}return "redirect:/index";
}

2. 接口Subject实现类DelegatingSubject的login方法

    public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
Subject subject = securityManager.login(this, token); // 此处调用SecurityManager登录,从此入口向下解析 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. 接口SecurityManager实现类DefaultSecurityManager的login方法

    /**
* First authenticates the {@code AuthenticationToken} argument, and if successful, constructs a
* {@code Subject} instance representing the authenticated account's identity.
* <p/>
* Once constructed, the {@code Subject} instance is then {@link #bind bound} to the application for
* subsequent access before being returned to the caller.
*
* @param token the authenticationToken to process for the login attempt.
* @return a Subject representing the authenticated user.
* @throws AuthenticationException if there is a problem authenticating the specified {@code token}.
*/
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = authenticate(token); // 验证凭证: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); // 创建Subject:createSubject(涉及到Session的创建,不在此文解析) onSuccessfulLogin(token, info, loggedIn); // rememberMe处理 return loggedIn;
}

对于1)的代码,继续向下分析,是使用Authenticator的委托来实现

    /**
* Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication.
*/
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}

实际调用的是抽象类AbstractAuthenticator的authenticate的方法

    public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {

        if (token == null) {
throw new IllegalArgumentException("Method argument (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);
if (log.isWarnEnabled())
log.warn(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;
}

查看方法doAuthenticate的实现,实际在子类ModularRealmAuthenticator

    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
Collection<Realm> realms = getRealms(); // 看到这里,大家应该明白realm的查找和执行时机了吧(在config中设置SecurityManager的realm) if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}

在demo中,我们使用的单一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);
}
AuthenticationInfo info = realm.getAuthenticationInfo(token); // 此处调用的还不是自定义的realm的方法,而是其父类AuthenticatingRealm
if (info == null) {
String msg = "Realm [" + realm + "] was unable to find account data for the " +
"submitted AuthenticationToken [" + token + "].";
throw new UnknownAccountException(msg);
}
return info;
}

AuthenticatingRealm的getAuthenticationInfo

    public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        AuthenticationInfo info = getCachedAuthenticationInfo(token); // 先从缓存取验证信息
if (info == null) {
//otherwise not cached, perform the lookup:
info = doGetAuthenticationInfo(token); // 此时才会真正的执行自定义的realm
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);
} if (info != null) {
assertCredentialsMatch(token, info); // 真正的密码校验是在realm执行完成之后的
} else {
log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
} return info;
}

大家这时候可能有一个疑问,为什么父类的protected方法会跑到子类执行呢?

这是因为执行的realm实例本身就是自定义的MyRealm,对于子类未实现而在抽象父类中实现的方法,当然是执行父类的方法,而对于已经覆盖的方法,当然也会走到子类的实现,这就是抽象和继承的好处!

接下来看自定义的realm

    /**
* 提供帐户信息,返回认证信息 (其实realm并不负责校验密码,而是负责把用户信息从数据源中取出来)
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String loginName = (String)authenticationToken.getPrincipal();
User user = userService.findUserByLoginName(loginName);
if(user == null) {
//用户不存在就抛出异常
throw new UnknownAccountException();
} //密码可以通过SimpleHash加密,然后保存进数据库。
//此处是获取数据库内的账号、密码、盐值,保存到登陆信息info中
return new SimpleAuthenticationInfo(
loginName,
user.getPassword(),
ByteSource.Util.bytes(Hex.decode(user.getSalt())),
getName());
}

4. 自定义realm执行完后,会返回到AuthenticatingRealm的getAuthenticationInfo进行密码校验assertCredentialsMatch (当然前提是取到了该用户)

5. 一步步回溯到DefaultSecurityManager的login方法中进行登录成功后的处理:session保存和rememberMe处理

(在config中设置SecurityManager的realm属性设置)

Shiro源码解析-登录篇的更多相关文章

  1. Shiro源码解析-Session篇

    上一篇Shiro源码解析-登录篇中提到了在登录验证成功后有对session的处理,但未详细分析,本文对此部分源码详细分析下. 1. 分析切入点:DefaultSecurityManger的login方 ...

  2. jQuery2.x源码解析(缓存篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 缓存是jQuery中的又一核心设计,jQuery ...

  3. jQuery2.x源码解析(构建篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 笔者阅读了园友艾伦 Aaron的系列博客< ...

  4. jQuery2.x源码解析(设计篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 这一篇笔者主要以设计的角度探索jQuery的源代 ...

  5. jQuery2.x源码解析(回调篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 通过艾伦的博客,我们能看出,jQuery的pro ...

  6. myBatis源码解析-类型转换篇(5)

    前言 开始分析Type包前,说明下使用场景.数据构建语句使用PreparedStatement,需要输入的是jdbc类型,但我们一般写的是java类型.同理,数据库结果集返回的是jdbc类型,而我们需 ...

  7. Spring源码解析 | 第二篇:Spring IOC容器之XmlBeanFactory启动流程分析和源码解析

    一. 前言 Spring容器主要分为两类BeanFactory和ApplicationContext,后者是基于前者的功能扩展,也就是一个基础容器和一个高级容器的区别.本篇就以BeanFactory基 ...

  8. myBatis源码解析-数据源篇(3)

    前言:我们使用mybatis时,关于数据源的配置多使用如c3p0,druid等第三方的数据源.其实mybatis内置了数据源的实现,提供了连接数据库,池的功能.在分析了缓存和日志包的源码后,接下来分析 ...

  9. myBatis源码解析-反射篇(4)

    前沿 前文分析了mybatis的日志包,缓存包,数据源包.源码实在有点难顶,在分析反射包时,花费了较多时间.废话不多说,开始源码之路. 反射包feflection在mybatis路径如下: 源码解析 ...

随机推荐

  1. 4.4.6 数组也能无锁:AtomicIntegerArray

    数组也可以实现cas操作,有以下几个类以及用法如下: public class AtomicTntegerArrayTest { public static void main(String[] ar ...

  2. clickonce发布winform必备组件

    ClickOnce 发布,在系统必备中勾选了 .NET Framework 4,并选择了"从与我的应用程序相同的位置下载系统必备组件"时,执行发布,会提示缺少很多文件 使用 Pac ...

  3. CodeForces 681C Heap Operations (模拟题,优先队列)

    题意:给定 n 个按顺序的命令,但是可能有的命令不全,让你补全所有的命令,并且要求让总数最少. 析:没什么好说的,直接用优先队列模拟就行,insert,直接放入就行了,removeMin,就得判断一下 ...

  4. iOS应用开发之Persistence持久化[转]

    持久化(Persistence) 持久化(Persistence)意思就是当你退出app的时候它还会存在.NSUserDefaults就是一个非常简单的持久化方案,不过这有限制,它只能是很小的东西,通 ...

  5. Matlab神经网络

    1. <MATLAB神经网络原理与实例精解> 2. B站:https://search.bilibili.com/all?keyword=matlab&from_source=na ...

  6. 关于Qt官方下载页的最新变动

    时间过得很快,现在Qt已经迎来了5.10版本,但是当我们去下载页下载对应安装包的时候,已经找不到之前的offline安装包了.你能够看到的只有在线安装包,并且我自己有做过测试,国内的网络基本上没有机会 ...

  7. 学习python4

    文件系统实现文件的增删改查 UnicodeDecodeError: 'gbk' codec can't decode byte 0x9a in position 8: illegal multibyt ...

  8. GCT感受

    GCT考试已经结束了,但是复习GCT的时候一直没来得及总结点什么,GCT考的比较基础,所以复习起来并不是特别费力,但是还是有一些东西值得我们去学习的. 对于GCT考试,一开始在报名的时候其实心里是挺抵 ...

  9. Git SSH Key

     一.设置Git的user name和email: $ git config --global user.name "hhl_vip" $ git config --global ...

  10. js 操作cookie cookie路径问题

    这里主要不是讲这个方法,js写cookie这种代码网上一抓一把,在使用的时候遇到一点问题,就是写的cookie 是有路径问题的,在user目录下可以使用跳转到另外一个目录下cookie,经过比较coo ...