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

 更新时间:2021年02月01日 15:46:55   作者:超人不会飞  
这篇文章主要介绍了shrio的认证(登录)过程,帮助大家更好的理解和使用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的认证(登录)过程的资料请关注脚本之家其它相关文章!

相关文章

  • Java Bigdecimal使用原理详解

    Java Bigdecimal使用原理详解

    这篇文章主要介绍了Java Bigdecimal使用原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • springboot项目中mapper.xml文件找不到的三种解决方案

    springboot项目中mapper.xml文件找不到的三种解决方案

    这篇文章主要介绍了springboot项目中mapper.xml文件找不到的三种解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • 永中文档在线转换服务Swagger调用说明

    永中文档在线转换服务Swagger调用说明

    这篇文章主要为大家介绍了永中文档在线转换服务Swagger调用说明,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • springboot网站应用使用第三方qq登录的实现过程

    springboot网站应用使用第三方qq登录的实现过程

    这篇文章主要介绍了springboot网站应用使用第三方qq登录,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • aop注解方式实现全局日志管理方法

    aop注解方式实现全局日志管理方法

    下面小编就为大家分享一篇aop注解方式实现全局日志管理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • Java实现经典游戏Flappy Bird的示例代码

    Java实现经典游戏Flappy Bird的示例代码

    Flappy Bird是13年红极一时的小游戏,即摁上键控制鸟的位置穿过管道间的缝隙。本文将用Java语言实现这一经典的游戏,需要的可以参考一下
    2022-02-02
  • 谈谈Java中自定义注解及使用场景

    谈谈Java中自定义注解及使用场景

    这篇文章主要介绍了谈谈Java中自定义注解及使用场景,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Jackson反序列化@JsonFormat 不生效的解决方案

    Jackson反序列化@JsonFormat 不生效的解决方案

    这篇文章主要介绍了Jackson反序列化@JsonFormat 不生效的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • Java实现短信验证码的示例代码

    Java实现短信验证码的示例代码

    本文主要介绍了Java实现短信验证码的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Eclipse项目出现红色叹号的解决方法

    Eclipse项目出现红色叹号的解决方法

    eclipse工程前面出现红色叹号都是由于eclipse项目、eclipse工程中,缺少了一些jar包等文件引起的,这篇文章主要给大家介绍了关于Eclipse项目出现红色叹号的解决方法,需要的朋友可以参考下
    2023-11-11

最新评论