详解shrio的认证(登录)过程

shrio是一个比较轻量级的安全框架,主要的作用是在后端承担认证和授权的工作。今天就讲一下shrio进行认证的一个过程。
首先先介绍一下在认证过程中的几个关键的对象:

  • Subject:主体

访问系统的用户,主体可以是用户、程序等,进行认证的都称为主体;

  • Principal:身份信息

是主体(subject)进行身份认证的标识,标识必须具有唯一性,如用户名、手机号、邮箱地址等,一个主体可以有多个身份,但是必须有一个主身份(Primary Principal)。

  • credential:凭证信息

是只有主体自己知道的安全信息,如密码、证书等。
接着我们就进入认证的具体过程:
首先是从前端的登录表单中接收到用户输入的token(username + password):

@RequestMapping("/login")
public String login(@RequestBody Map user){
  Subject subject = SecurityUtils.getSubject();
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.get("email").toString(), user.get("password").toString());
   try {
      subject.login(usernamePasswordToken);
   } catch (UnknownAccountException e) {
      return "邮箱不存在!";
   } catch (AuthenticationException e) {
      return "账号或密码错误!";
   }
    return "登录成功!";
  }

这里的usernamePasswordToken(以下简称token)就是用户名和密码的一个结合对象,然后调用subject的login方法将token传入开始认证过程。
接着会发现subject的login方法调用的其实是securityManager的login方法:

Subject subject = securityManager.login(this, token);

再往下看securityManager的login方法内部:

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);
   onSuccessfulLogin(token, info, loggedIn);
   return loggedIn;
}

上面代码的关键在于:

info = authenticate(token);

即将token传入authenticate方法中得到一个AuthenticationInfo类型的认证信息。
以下是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;
}

首先就是判断token是否为空,不为空再将token传入doAuthenticate方法中:

protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
  assertRealmsConfigured();
  Collection<Realm> realms = getRealms();
  if (realms.size() == 1) {
    return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
  } else {
    return doMultiRealmAuthentication(realms, authenticationToken);
  }
}

这一步是判断是有单个Reaml验证还是多个Reaml验证,单个就执行doSingleRealmAuthentication()方法,多个就执行doMultiRealmAuthentication()方法。
一般情况下是单个验证:

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);
  if (info == null) {
    String msg = "Realm [" + realm + "] was unable to find account data for the " +
        "submitted AuthenticationToken [" + token + "].";
    throw new UnknownAccountException(msg);
  }
  return info;
}

这一步中首先判断是否支持Realm,只有支持Realm才调用realm.getAuthenticationInfo(token)获取info。

public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  AuthenticationInfo info = getCachedAuthenticationInfo(token);
  if (info == null) {
    //otherwise not cached, perform the lookup:
    info = doGetAuthenticationInfo(token);
    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);
  } else {
    log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
  }
  return info;
}

首先查看Cache中是否有该token的info,如果有,则直接从Cache中去即可。如果是第一次登录,则Cache中不会有该token的info,需要调用doGetAuthenticationInfo(token)方法获取,并将结果加入到Cache中,方便下次使用。而这里调用的doGetAuthenticationInfo()方法就是我们在自己重写的方法,具体的内容是自定义了对拿到的这个token的一个处理的过程:

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  if (authenticationToken.getPrincipal() == null)
    return null;
  String email = authenticationToken.getPrincipal().toString();
  User user = userService.findByEmail(email);
  if (user == null)
    return null;
  else return new SimpleAuthenticationInfo(email, user.getPassword(), getName());
}

这其中进行了几步判断:首先是判断传入的用户名是否为空,在判断传入的用户名在本地的数据库中是否存在,不存在则返回一个用户名不存在的Exception。以上两部通过之后生成一个包括传入用户名和密码的info,注意此时关于用户名的验证已经完成,接下来进入对密码的验证。
将这一步得到的info返回给getAuthenticationInfo方法中的

assertCredentialsMatch(token, info);

此时的info是正确的用户名和密码的信息,token是输入的用户名和密码的信息,经过前面步骤的验证过程,用户名此时已经是真是存在的了,这一步就是验证输入的用户名和密码的对应关系是否正确。

protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
  CredentialsMatcher cm = getCredentialsMatcher();
  if (cm != null) {
    if (!cm.doCredentialsMatch(token, info)) {
      //not successful - throw an exception to indicate this:
      String msg = "Submitted credentials for token [" + 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.");
  }
}

上面步骤就是验证token中的密码的和info中的密码是否对应的代码。这一步验证完成之后,整个shrio认证的过程就结束了。

以上就是详解shrio的认证(登录)过程的详细内容,更多关于shrio的认证(登录)过程的资料请关注我们其它相关文章!

(0)

相关推荐

  • Apache Shrio安全框架实现原理及实例详解

    一.Shiro整体概述 1.简介 Apache Shiro是Java的一个安全框架,功能强大,使用简单,Shiro为开发人员提供了一个直观而全面的认证(登录),授权(判断是否含有权限),加密(密码加密)及会话管理(Shiro内置Session)的解决方案. 2.Shiro组件 3.Shiro架构 3.1 外部架构(以应用程序角度) 3.2 内部架构 4. Shiro的过滤器 过滤器简称 对应的java类 anon org.apache.shiro.web.filter.authc.Anonymo

  • Spring-boot结合Shrio实现JWT的方法

    本文介绍了Spring-boot结合Shrio实现JWT的方法,分享给大家,具体如下: 关于验证大致分为两个方面: 用户登录时的验证: 用户登录后每次访问时的权限认证 主要解决方法:使用自定义的Shiro Filter 项目搭建: 这是一个spring-boot 的web项目,不了解spring-boot的项目搭建,请google. pom.mx引入相关jar包 <!-- shiro 权限管理 --> <dependency> <groupId>org.apache.s

  • 详解shrio的认证(登录)过程

    shrio是一个比较轻量级的安全框架,主要的作用是在后端承担认证和授权的工作.今天就讲一下shrio进行认证的一个过程. 首先先介绍一下在认证过程中的几个关键的对象: Subject:主体 访问系统的用户,主体可以是用户.程序等,进行认证的都称为主体: Principal:身份信息 是主体(subject)进行身份认证的标识,标识必须具有唯一性,如用户名.手机号.邮箱地址等,一个主体可以有多个身份,但是必须有一个主身份(Primary Principal). credential:凭证信息 是只

  • 详解微信小程序 登录获取unionid

    详解微信小程序 登录获取unionid 首先公司开发了小程序, 公众号网页和app等, 之前都是用的openid来区分用户, 但openid只能标识用户在当前小程序或公众号里唯一, 我们希望用户可以在公司各个产品(比如公众号, 小程序, app里的微信登录)之间, 可以保持用户的唯一性, 还好微信给出了unionid. 下面分两步介绍一下 微信小程序 获取unionid的过程. 1. 首先 在微信公众平台注册小程序 , 然后在小程序上模拟登录流程. 注 : 这里只是简单登录流程, 实际中需要维护

  • Django 自定义权限管理系统详解(通过中间件认证)

    1. 创建工程文件, 修改setting.py文件 django-admin.py startproject project_name 特别是在 windows 上,如果报错,尝试用 django-admin 代替 django-admin.py 试试 setting.py 最终的配置文件 import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =

  • 详解vue身份认证管理和租户管理

    概述 功能模块的开发往往是最容易的,但是要处理好每个细节就不容易了.就拿这里的身份认证管理模块来说,看似很简单,因为后端接口都是ABP模板里现成的,前端部分无非就是写界面,调接口,绑数据:但是看一下ABP Angular版本的代码,就会发现他其实是有很多细节方面的处理的. 回到vue,因为前端部分的代码文件太多,下面只列出一些需要注意的细节,其他的像vue组件.表格.表单.数据绑定.接口请求之类的其实都差不多就不说了. 按钮级权限 前面章节中实现了菜单权限的控制,按钮权限的道理也是一样的.判断a

  • 详解如何用Python登录豆瓣并爬取影评

    目录 一.需求背景 二.功能描述 三.技术方案 四.登录豆瓣 1.分析豆瓣登录接口 2.代码实现登录豆瓣 3.保存会话状态 4.这个Session对象是我们常说的session吗? 五.爬取影评 1.分析豆瓣影评接口 2.爬取一条影评数据 3.影评内容提取 4.批量爬取 六.分析影评 1.使用结巴分词 七.总结 上一篇我们讲过Cookie相关的知识,了解到Cookie是为了交互式web而诞生的,它主要用于以下三个方面: 会话状态管理(如用户登录状态.购物车.游戏分数或其它需要记录的信息) 个性化

  • 详解mongoDB主从复制搭建详细过程

    详解mongoDB主从复制搭建详细过程 实验目的搭建mongoDB主从复制 主 192.168.0.4 从 192.168.0.7 mongodb的安装 1: 下载mongodb www.mongodb.org 下载最新的stable版 查看自己服务器 适合哪个种方式下载(wget 不可以的 可以用下面方式下载) wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.0.5.tgz curl -O -L https

  • 详解Spring ApplicationContext加载过程

    1.找准入口,使用ClassPathXmlApplicationContext的构造方法加载配置文件,用于加载classPath下的配置文件 //第一行,执行完成之后就完成了spring配置文件的加载,刷新spring上下文 ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext( "classpath:spring-mvc.xml"); //获取实例Bean Person person=con

  • 详解Java对象创建的过程及内存布局

    一.对象的内存布局 对象头 对象头主要保存对象自身的运行时数据和用于指定该对象属于哪个类的类型指针. 实例数据 保存对象的有效数据,例如对象的字段信息,其中包括从父类继承下来的. 对齐填充 对齐填充不是必须存在的,没有特别的含义,只起到一个占位符的作用. 二.对象的创建过程 实例化一个类的对象的过程是一个典型的递归过程. 在准备实例化一个类的对象前,首先准备实例化该类的父类,如果该类的父类还有父类,那么准备实例化该类的父类的父类,依次递归直到递归到Object类. 此时,首先实例化Object类

  • Java详解entity转换到vo过程

    目录 起因 1. 将Entity转化为Vo 2. 将List<Entity>转换为List<Vo> 封装到工具类后使用 性能以及原理 ConvertUtil工具类源码 起因 使用 mybatis-plus 操作后获得的数据类型为 Entity,但是前端界面往往需要展示一些其他的字段数据,此时就需要 将 Entity 转化为 Vo. 那么他们三者的关系是什么呢?面向的使用对象不同 entity: 对应数据库表模型 vo: 对应需要返回到前端的数据模型 dto: 对应后台内部调用的数据

  • 详解PHP实现HTTP服务器过程

    目录 原生Socket编程 流行项目 Workerman系 Swoole系 ReactPHP系 AMPHP系 swow 总结 PHP并非不能实现HTTP服务,一般来讲,这叫网络编程或Socket编程.在学习到其他语言的这部分的时候,一般的思路就是如何监听TCP实现一个服务器,并处理HTTP协议. PHP也可以这样做,同时一般伴随着高性能这样的关键字出现. 原生Socket编程 我们可以通过PHP的Socket函数,很简单的实现出HTTP服务. function run() { //创建服务端的s

随机推荐