shiro原理之认证

前言

这几天因为项目要用到鉴权,很久以前就听说过shiro了,但是之前一直要求用的是Spring Security,所以没机会接触Shiro,这次有机会我用了下Shiro,确实如网上说的一样,轻量级、微框架、功能强大。当然,刚开始我也只是网上看了看官网,然后找了几篇写的比较好的博客教程,按照教程一点点把Shiro接入到项目中去,也实现了想要的功能,然而,可能是开发时间长了吧,现在功能实现了却不满足,很想知道他里面到底是怎么实现的,揪心了很多天,也查了很多资料,写了几个Demo试了试,直接看源码我现在能力是不行的,只是通过打断点一步一步的方式来理解其中的原理 o(╥﹏╥)o,作了个比较浅的框架理解吧,为了养成记录的好习惯,这篇文章也是一个结果吧。

简述原理

Shiro是一个流行了很长时间的一个轻量级鉴权框架了,也是交给了Apache基金会来维护了,网上以及官网也有许多相关的文档对其叙述以及解读,这里也就从网上摘抄一点来简单的说明下吧。

框架结构

Shiro框架结构

Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;

Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;

Session Management:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;

Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;

Web Support:Web 支持,可以非常容易的集成到 Web 环境;

Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;

Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;

Testing:提供测试支持;

Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;

Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了

Shiro 不会去维护用户、维护权限;这些需要我们自己去设计 / 提供;然后通过相应的接口注入给 Shiro 即可。

鉴权流程

img

我们可以看到:应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject;其每个 API 的含义:

Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;

SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,你可以把它看成 DispatcherServlet 前端控制器;

Realm:域,Shiro 从从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。

从上图中我们可以看出,对于Shiro应用来说他的鉴权过程有如下几个步骤:

  1. 应用代码通过SecurityUtils.getSubject()来获取到subject
  2. subject调用一些方法(比如login等)来委托SecurityManager来进行认证和授权。
  3. SecurityManager通过注入的Realm来获取用户信息来实现认证和授权

一起鉴权

对于Shiro的原理刚刚我们简单介绍了下,但是程序中具体是如何实现的呢?我们跟着代码一起来看看吧。

step 1 登录

鉴权就是查看资源的调用方是否有相关的权限来调用相关接口或获取资源。所以我们首先要进行登录。

// 自己编写的登录方法
public String login(String userName,String password){
        /**
         * 这里的注入的Token类型 就是 出入Realm中doGetAuthenticationInfo的参数类型
         */
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            //进行验证,这里可以捕获异常,然后返回对应信息
            subject.login(usernamePasswordToken);
            // 检测角色
            //  subject.checkRole("admin");
            // 检测权限
            //  subject.checkPermissions("query", "add");
        } catch (UnknownAccountException e) {
            return "用户名不存在!";
        } catch (AuthenticationException e) {
            System.out.println(e.getLocalizedMessage());
            return "账号或密码错误!";
        } catch (AuthorizationException e) {
            return "没有权限";
        } 
        return "Hello,"+userName;
    }

这里登录方法中将登录验证委托给了Subject的login方法,Subject的login方法的签名为:

void login(AuthenticationToken authenticationToken) throws AuthenticationException;

因为AuthenticationToken是一个接口,所以login的参数是传入实现了AuthenticationToken接口的类,上面我们使用了Shiro自带的UsernamePasswordToken类,传入用户名和密码,实例化了一个UsernamePasswordToken的实例,并传入subject的login方法中。

其中,对于AuthenticationToken接口,Shiro内置了一些实现,如下图:

authenticationToken

使用自带的UsernamePasswordToken可能不满足我们的要求,如果要自定义Token的话只需要创建一个类实现了AuthenticationToken即可。

在调用subject.login()之后程序到了哪里了呢?我们查看Subject的实现类 DelegatingSubject 中 login方法是如何实现的:

// org.apache.shiro.subject.support.DelegatingSubject.java
      public void login(AuthenticationToken token) throws AuthenticationException {
this.clearRunAsIdentitiesInternal();
// 先是找到 securityManager,然后将验证相关的功能委托给它
Subject subject = this.securityManager.login(this, token);
// 下面基本是使用securityManager验证后返回的subject将他的一些认证信息保存到自己的属性中去。
String host = null;
PrincipalCollection principals;
if (subject instanceof DelegatingSubject) {
   DelegatingSubject delegating = (DelegatingSubject)subject;
   principals = delegating.principals;
   host = delegating.host;
} else {
   principals = subject.getPrincipals();
}

if (principals != null && !principals.isEmpty()) {
   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 = this.decorate(session);
   } else {
       this.session = null;
   }

} else {
   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);
}
}

刚刚我们看到了验证的功能又委托给了SecurityManager的login方法,SecurityManager也只是一个接口类,其中DefaultSecurityManager继承了SessionSecurityManager,DefaultSecurityManager也是Shiro中一般默认注入的SecurityManager。

DefaultSecurityManager

我们查看它的实现类DefaultSecurityManager中的login方法:

  // org.apache.shiro.mgt.DefaultSecurityManager.java
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
// 这里调用了AuthoriztingSecurityManager的authenticate方法进行验证
info = this.authenticate(token);
} catch (AuthenticationException var7) {
AuthenticationException ae = var7;

try {
this.onFailedLogin(token, ae, subject);
} catch (Exception var6) {
if (log.isInfoEnabled()) {
 log.info("onFailedLogin method threw an exception.  Logging and propagating original AuthenticationException.", var6);
}
}

throw var7;
}

Subject loggedIn = this.createSubject(token, info, subject);
this.onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}

AuthoriztingSecurityManager的authenticate方法

// org.apache.shiro.mgt.AuthoriztingSecurityManager.java
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
  // 这里调用了 org.apache.shiro.authc.Authenticator实现类AbstractAuthenticator的authenticate方法
  return this.authenticator.authenticate(token);
}
// org.apache.shiro.authc.AbstractAuthenticator.java
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
if (token == null) {
   throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
} else {
   log.trace("Authentication attempt received for token [{}]", token);

   AuthenticationInfo info;
   try {
       // 这里将token又代理给实现类来进行验证,shiro中调用的是ModularRealmAuthenticator类中的doAuthenticate方法
       info = this.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 var8) {
       AuthenticationException ae = null;
       if (var8 instanceof AuthenticationException) {
           ae = (AuthenticationException)var8;
       }

       if (ae == null) {
           String msg = "Authentication failed for token submission [" + token + "].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).";
           ae = new AuthenticationException(msg, var8);
           if (log.isWarnEnabled()) {
               log.warn(msg, var8);
           }
       }

       try {
           this.notifyFailure(token, ae);
       } catch (Throwable var7) {
           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, var7);
           }
       }

       throw ae;
   }

   log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);
   this.notifySuccess(token, info);
   return info;
}
}

protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken var1) throws AuthenticationException;
 // org.apache.shiro.authc.pam.ModularRealmAuthenticator.java
 protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        // 支持多个Realm来进行验证
        Collection<Realm> realms = this.getRealms();
        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
// 对单个Realm验证token
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);
        } else {
          // 调用了realm的getAuthenticationInfo方法进行验证,Realm的实现类是AuthenticatingRealm
            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);
            } else {
                return info;
            }
        }
    }


  // org.apache.shiro.realm.AuthenticatingRealm 
  public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo info = this.getCachedAuthenticationInfo(token);
        if (info == null) {
           // 这里将认证最后委托给实现了doGetAuthenticationInfo的子类中。
            info = this.doGetAuthenticationInfo(token);
            log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
            if (token != null && info != null) {
                this.cacheAuthenticationInfoIfPossible(token, info);
            }
        } else {
            log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
        }

        if (info != null) {
            this.assertCredentialsMatch(token, info);
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }

 protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;

step 2 Realm认证

上一步我们分析了,总体是Subject将token传给SecurityManager来认证,而SecurityManager有将token传给Realm去验证,最终落实到doGetAuthenticationInfo方法中,而实际过程中Realm由我们自己编写,该Realm要实现AuthenticatingRealm接口,比如以下Realm:

CustomUserRealm
import com.martain.simpleshiroinspringboot.model.User;
import com.martain.simpleshiroinspringboot.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * 自定义Realm
 * @author martain
 */
public class CustomUserRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    /**
     * 鉴权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo...");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    } 
    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo...");
        // 由于我们在subject.login时传入的UsernamePassword类型的Token,所以这里可以强转为UsernamePassword类型
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 下面就是自定义的验证流程了
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());
        User user = userService.findByUserName(username);
        if (user == null){
            throw new AuthenticationException("用户不存在");
        }
        if (!user.getPassword().equalsIgnoreCase(password))
        {
            throw new AuthenticationException("用户密码错误");
        }
        // 验证完成之后,需要返回一个AuthenticationInfo,这里返回的SimpleAuthenticationInfo实例,第一个参数是principal,
        // 我们传入的是User类型的user,在后面调用SecurityUtils.getSubject().getPrincipal();获得的就是这个user
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password, getName());
        return simpleAuthenticationInfo;
    }
} 

step 3 获取当前用户

public User getUserInfo(){
  User user = (User) SecurityUtils.getSubject().getPrincipal();
  return user;
}

在Realm调用完doGetAuthenticationInfo返回AuthenticationInfo时传入的principal,这个principal最后保存到了Subject中去,所以可以对Principal进行强转。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341