本文以循序渐进的方式解析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. ubuntu启动流程和要读取相关文件

    当前系统环境为:linux mint mate 17.1(基于ubuntu14.04的衍生版) 查阅资料后总结如下: 首先: /etc/rc.d链接目标为:/etc /etc/rc*.d文件夹中的脚本 ...

  2. mongodb新建用户,

    1.用管理 员用户登录mongoDB use hzb_test db.createUser({user: "hzb",pwd: "hzb",roles: [{ ...

  3. CodeForces 540B School Marks (贪心)

    题意:先给定5个数,n,  k, p, x, y.分别表示 一共有 n 个成绩,并且已经给定了 k 个,每门成绩 大于0 小于等于p,成绩总和小于等于x, 但中位数大于等于y.让你找出另外的n-k个成 ...

  4. mybatis_入门程序

    Mybatis入门 (一).程序环境 1.jar包 2.classpath目录下建立SqlMapConfig.xml. mybatis的配置文件.全部设置有如下 同时,数据库的参数可以用propert ...

  5. 在线测试正则表达式工具 jQuery.Validate验证库

    http://www.jb51.net/tools/zhengze.html http://www.cnblogs.com/weiqt/articles/2013800.html  

  6. Utimate Visual 2013 突然间无法新建项目工程解决

    问题: 我用的Win7 安装的VS2013,这一段时间用的好好的,突然间新建工程师向导页面跳转不过去... 解决: 参考:http://stackoverflow.com/questions/1225 ...

  7. K倍区间 蓝桥杯

    问题描述 给定一个长度为N的数列,A1, A2, ... AN,如果其中一段连续的子序列Ai, Ai+1, ... Aj(i <= j)之和是K的倍数,我们就称这个区间[i, j]是K倍区间. ...

  8. unigui的UnimDatePicker控件使用经验

    最近使用unigui的UnimDatePicker控件遇到只能选择当年之前的年份和日期及日期选择界面不能显示中文的问题,经以下设置就能正常使用.1.UnimDatePicker月份显示中文  unim ...

  9. Spring.NET 整合Nhibernate

    因为最近无意中学了AOP ,所以想一探究竟,看看.net里这个Spring.Net 到底是怎么回事,请有需要的童鞋往下,不需要的请alt+w.因为是先配置的 Nhibernate 所以就从这个开始.开 ...

  10. vue的props 属性类似于bug的东西

    /* * @Author: shs * @Date: 2019-04-19 17:48:39 * @Last Modified by: shs * @Last Modified time: 2019- ...