源码分析shiro认证授权流程

2023-11-15

1. shiro介绍

Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能: 

  • 认证 - 用户身份识别,常被称为用户“登录”;
  • 授权 - 访问控制;
  • 密码加密 - 保护或隐藏数据防止被偷窥;
  • 会话管理 - 每用户相关的时间敏感的状态。

对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。

2. shiro源码概况

    先要了解shiro的基本框架(见http://www.cnblogs.com/davidwang456/p/4425145.html)。

    然后看一下各个组件之间的关系:

一下内容参考:http://kdboy.iteye.com/blog/1154644

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。 
Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。 

SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。 

Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。 
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。 
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。

Shiro主要组件还包括: 
Authenticator :认证就是核实用户身份的过程。这个过程的常见例子是大家都熟悉的“用户/密码”组合。多数用户在登录软件系统时,通常提供自己的用户名(当事人)和支持他们的密码(证书)。如果存储在系统中的密码(或密码表示)与用户提供的匹配,他们就被认为通过认证。 
Authorizer :授权实质上就是访问控制 - 控制用户能够访问应用中的哪些内容,比如资源、Web页面等等。 
SessionManager :在安全框架领域,Apache Shiro提供了一些独特的东西:可在任何应用或架构层一致地使用Session API。即,Shiro为任何应用提供了一个会话编程范式 - 从小型后台独立应用到大型集群Web应用。这意味着,那些希望使用会话的应用开发者,不必被迫使用Servlet或EJB容器了。或者,如果正在使用这些容器,开发者现在也可以选择使用在任何层统一一致的会话API,取代Servlet或EJB机制。 
CacheManager :对Shiro的其他组件提供缓存支持。 

3. 做一个demo,跑shiro的源码,从login开始:

第一步:用户根据表单信息填写用户名和密码,然后调用登陆按钮。内部执行如下:

复制代码

    UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(), loginForm.getPassphrase());

    token.setRememberMe(true);

    Subject currentUser = SecurityUtils.getSubject();

    currentUser.login(token);

复制代码

第二步:代理DelegatingSubject继承Subject执行login

复制代码

 public void login(AuthenticationToken token) throws AuthenticationException {
        clearRunAsIdentitiesInternal();
        Subject subject = securityManager.login(this, token);

        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;
        }
    }

复制代码

第三步:调用DefaultSecurityManager继承SessionsSecurityManager执行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;
    }

复制代码

第四步:认证管理器AuthenticatingSecurityManager继承RealmSecurityManager执行authenticate方法:

    /**
     * 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继承Authenticator, LogoutAware 执行authenticate方法:

复制代码

public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {

        if (token == null) {
            throw new IllegalArgumentException("Method argumet (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);
            }
            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;
    }

复制代码

第六步:ModularRealmAuthenticator继承AbstractAuthenticator执行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);
        }
    }

复制代码

接着调用:

复制代码

    /**
     * Performs the authentication attempt by interacting with the single configured realm, which is significantly
     * simpler than performing multi-realm logic.
     *
     * @param realm the realm to consult for AuthenticationInfo.
     * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
     * @return the AuthenticationInfo associated with the user account corresponding to the specified {@code 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);
        }
        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;
    }

复制代码

第七步:AuthenticatingRealm继承CachingRealm执行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);  //缓存中读不到,则到数据库或者ldap或者jndi等去读
            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;
    }

复制代码

1. 从缓存中读取的方法:

复制代码

    /**
     * Checks to see if the authenticationCache class attribute is null, and if so, attempts to acquire one from
     * any configured {@link #getCacheManager() cacheManager}.  If one is acquired, it is set as the class attribute.
     * The class attribute is then returned.
     *
     * @return an available cache instance to be used for authentication caching or {@code null} if one is not available.
     * @since 1.2
     */
    private Cache<Object, AuthenticationInfo> getAuthenticationCacheLazy() {

        if (this.authenticationCache == null) {

            log.trace("No authenticationCache instance set.  Checking for a cacheManager...");

            CacheManager cacheManager = getCacheManager();

            if (cacheManager != null) {
                String cacheName = getAuthenticationCacheName();
                log.debug("CacheManager [{}] configured.  Building authentication cache '{}'", cacheManager, cacheName);
                this.authenticationCache = cacheManager.getCache(cacheName);
            }
        }

        return this.authenticationCache;
    }

复制代码

2. 从数据库中读取的方法:

JdbcRealm继承 AuthorizingRealm执行doGetAuthenticationInfo方法

复制代码

 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        Connection conn = null;
        SimpleAuthenticationInfo info = null;
        try {
            conn = dataSource.getConnection();

            String password = null;
            String salt = null;
            switch (saltStyle) {
            case NO_SALT:
                password = getPasswordForUser(conn, username)[0];
                break;
            case CRYPT:
                // TODO: separate password and hash from getPasswordForUser[0]
                throw new ConfigurationException("Not implemented yet");
                //break;
            case COLUMN:
                String[] queryResults = getPasswordForUser(conn, username);
                password = queryResults[0];
                salt = queryResults[1];
                break;
            case EXTERNAL:
                password = getPasswordForUser(conn, username)[0];
                salt = getSaltForUser(username);
            }

            if (password == null) {
                throw new UnknownAccountException("No account found for user [" + username + "]");
            }

            info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
            
            if (salt != null) {
                info.setCredentialsSalt(ByteSource.Util.bytes(salt));
            }

        } catch (SQLException e) {
            final String message = "There was a SQL error while authenticating user [" + username + "]";
            if (log.isErrorEnabled()) {
                log.error(message, e);
            }

            // Rethrow any SQL errors as an authentication exception
            throw new AuthenticationException(message, e);
        } finally {
            JdbcUtils.closeConnection(conn);
        }

        return info;
    }

复制代码

接着调用sql语句:

复制代码

 private String[] getPasswordForUser(Connection conn, String username) throws SQLException {

        String[] result;
        boolean returningSeparatedSalt = false;
        switch (saltStyle) {
        case NO_SALT:
        case CRYPT:
        case EXTERNAL:
            result = new String[1];
            break;
        default:
            result = new String[2];
            returningSeparatedSalt = true;
        }
        
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(authenticationQuery);
            ps.setString(1, username);

            // Execute query
            rs = ps.executeQuery();

            // Loop over results - although we are only expecting one result, since usernames should be unique
            boolean foundResult = false;
            while (rs.next()) {

                // Check to ensure only one row is processed
                if (foundResult) {
                    throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
                }

                result[0] = rs.getString(1);
                if (returningSeparatedSalt) {
                    result[1] = rs.getString(2);
                }

                foundResult = true;
            }
        } finally {
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeStatement(ps);
        }

        return result;
    }

复制代码

其中authenticationQuery定义如下:

 protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;
 protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";

4. 小结

Apache Shiro 是功能强大并且容易集成的开源权限框架,它能够完成认证、授权、加密、会话管理等功能。认证和授权为权限控制的核心,简单来说,“认证”就是证明你是谁? Web 应用程序一般做法通过表单提交用户名及密码达到认证目的。“授权”即是否允许已认证用户访问受保护资源。

参考文献:

http://kdboy.iteye.com/blog/1154644

http://www.ibm.com/developerworks/cn/java/j-lo-shiro/ 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

源码分析shiro认证授权流程 的相关文章

  • 基于ESB权限初始化流程开发总结

    在集团信息化系统的建设过程中 由于应用系统数量日益增多 很多集团缺少一个能有效地将众多系统身份认证 账号管理 授权等功能集成的软件系统 由此IDM应运而生 在IDM中统一权限的功能资源模块是对下游系统的平台进行功能资源的统一管控 在管控之前

随机推荐

  • HTTP学习——网关

    网关可以作为一种翻译器使用 抽象出了一种能够到达资源的方法 网关和代理的区别 代理连接的是两个或多个使用相同协议的应用程序 而网关连接的则是两个或多个使用不同协议的端点 网关扮演的是 协议转换器 的角色 Web网关在一侧使用HTTP协议 在
  • 离散数学 --- 命题逻辑 -- 命题符号化与命题公式

    第一部分 命题符号化及其应用 1 等价连接词中 P Q同为真同为假时为真 真假不同时为假 下面是各个联结词的真值表 复合命题的真值只取决于通过联结词构成他的简单命题的真值 与简单命题的内容无关 比如 中国在地球上且太阳东升西落 这是一个复合
  • 记录DHCP IPV6遇到的问题(一)

    进行DHCP IPV6连接的时候 经常遇到设备获取过一次地址后 在短时间内再次重新主动进行一次DHCP IPV6连接 会连接失败 从抓包来分析就是上行服务器不响应 通过与服务器方的沟通 了解到一点 服务器会记录请求设备的mac和DUID 是
  • SpringMVC的架构有什么优势?——视图与模型(二)

    前言 作者主页 雪碧有白泡泡 个人网站 雪碧的个人网站 推荐专栏 java一站式服务 React从入门到精通 前端炫酷代码分享 从0到英雄 vue成神之路 uniapp 从构建到提升 从0到英雄 vue成神之路 解决算法 一个专栏就够了 架
  • 一文拆解Faas的真实案例

    欢迎大家前往腾讯云 社区 获取更多腾讯海量技术实践干货哦 本文来自腾讯云技术沙龙 本次沙龙主题为Serverless架构开发与SCF部署实践 刘敏洁 具有多年云计算行业经验 曾任职于华为 UCloud等企业担任产品开发 产品经理 目前负责腾
  • meedu二次开发:企业内部使用 必须登录之后才能查看里面内容

    meedu二次开发 修改成企业内部培训系统功能 用户必须登录之后才能查看里面课程内容
  • C语言第五章第4节用for语句实现循环学习导案

    课 题 5 4 用for语句实现循环 课时安排 2课时 课 型 新授 学 习目标 掌握for循环语句的一般形式 掌握for循环语句的执行过程 重点 for循环语句的一般形式 难点 理解for循环语句的执行过程并会做题 导 学 流 程 复备或
  • 实习日志3.22

    今天是实习的第一天 主要做了以下工作 1 安装vs2017 在csdn直接下载安装包 官网找不到2017版本的社区版 2 配置opencv编译环境 4 2 0版本 推荐b站up3 3 遇到了bug 找不到opencv core420d dd
  • PyTorch报错insufficient shared memory (shm)

    报错 ERROR Unexpected bus error encountered in worker This might be caused by insufficient shared memory shm ERROR Unexpec
  • 高并发分布式架构演进

    架构演进过程如下 单机架构 第一次演进 Tomcat与数据库分开部署 第二次演进 引入本地缓存和分布式缓存 第三次演进 引入反向代理实现负载均衡 第四次演进 数据库读写分离 第五次演进 数据库按业务分库 第六次演进 把大表拆分为小表 第七次
  • 哈工大计算机系统大作业

    哈工大计算机系统大作业 摘要 本文主要阐述在Linux系统下hello程序的生命周期 了解hello程序从hello c经过预处理 编译 汇编 链接生成可执行文件的全过程 结合课本的知识详细阐述计算机系统是如何对hello进行进程管理 存储
  • git commit 提交失败

    git commit 之后提示 原因 对项目进行git 操作的时候 会调用到pre commit的插件 它对代码风格进行检查 不符合规范则取消commit 操作 导致无法push 解决方案 方案一 git commit no verify
  • 打包aab教程,模拟器安装aab教程

    一 aab 打包 Android App Bundle aab 是谷歌新的安卓安装文件 其实也就是根据 cpu 架构和语言等 切分多个 apk 以减少包体体积 aab 打包有以下两种方式 AS 打包 Android Studio 打包 类型
  • Stack的三种含义

    学习编程的时候 经常会看到stack这个词 它的中文名字叫做 栈 理解这个概念 对于理解程序的运行至关重要 容易混淆的是 这个词其实有三种含义 适用于不同的场合 必须加以区分 含义一 数据结构 stack的第一种含义是一组数据的存放方式 特
  • 高通 Msm835平台充电功能的开发与调试

    目录 平台充电相关代码 835平台kernel充电相关代码 关机充电的系统相关代码 835平台UEFI 充电相关代码 835平台电池曲线 电池曲线大体内容如下 kernel 电池曲线的提交 XBL 关于充电曲线的提交 充电相关调试方法 充电
  • js逆向学习路线指南

    1 js基础教程 耗时2个星期 2个月 视基础而定 主要掌握用js进行程序设计 以及dom相关的知识 反复看 反复编程 并做好笔记 教程 https wangdoc com javascript index html 2 开始进行实战 多看
  • LeetCode 86. 分隔链表 Partition List(C语言)

    题目描述 给定一个链表和一个特定值 x 对链表进行分隔 使得所有小于 x 的节点都在大于或等于 x 的节点之前 你应当保留两个分区中每个节点的初始相对位置 示例 输入 head 1 gt 4 gt 3 gt 2 gt 5 gt 2 x 3
  • 【Dubbo】Dubbo(一)为什么使用Dubbo?

    Dubbo Dubbo是一款Java RPC框架 如何将应用打包并部署到服务器上 之前的单一应用架构 可以部署到多个服务器上 每次修改或扩展某一处功能都要将整个应用重新打包并部署到多台服务器上 协同开发时都改这一个应用 不利于开发与维护 当
  • 解决PyCharm ImportError: No module named tensorflow 详解

    运行 TensorFlow MNIST 实验程序时出错 报错原因 所用到的python解释器和我们当前PyCharm所用的python解释器不一致说导致 故解决方案 将PyCharm的解释器更改为TensorFlow下的python解释器
  • 源码分析shiro认证授权流程

    1 shiro介绍 Apache Shiro是一个强大易用的Java安全框架 提供了认证 授权 加密和会话管理等功能 认证 用户身份识别 常被称为用户 登录 授权 访问控制 密码加密 保护或隐藏数据防止被偷窥 会话管理 每用户相关的时间敏感