温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

​springboot中集成shiro框架的方法

发布时间:2020-05-29 16:06:01 来源:亿速云 阅读:233 作者:鸽子 栏目:编程语言

springboot中集成shiro框架

关于shior框架的介绍,需要引入相关jar如下:

    <!--shiro核心jar from www.1b23.com-->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.0</version>
    </dependency>
    <!--实现session共享。缓存等-->
    <dependency>
        <groupId>org.crazycake</groupId>
        <artifactId>shiro-redis</artifactId>
        <version>3.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

未整合Spring/SpringBoot以前,是需要在Web.xml中定义org.apache.shiro.web.servlet.ShiroFilter过滤器的
Shiro的初始化工作在web.xml中设置监听器完成

<listener>   
 <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
 </listener>
 <filter>
     <filter-name>ShiroFilter</filter-name>
     <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
 </filter>
 <filter-mapping>
     <filter-name>ShiroFilter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>
 Shiro 的 EnvironmentLoaderListener 就是一个典型的 ServletContextListener,它也是整个 Shiro Web 应用的入口 。

EventListener 是一个标志接口,里面没有任何的方法,Servlet 容器中所有的 Listener 都要继承这个接口(这是 Servlet 规范)。


ServletContextListener 是一个 ServletContext 的监听器,用于监听容器的启动与关闭事件,包括如下两个方法:
void contextInitialized(ServletContextEvent sce); // 当容器启动时调用
void contextDestroyed(ServletContextEvent sce); // 当容器关闭时调用

可以从 ServletContextEvent 中直接获取 ServletContext 对象。

EnvironmentLoaderListener 不仅实现了 ServletContextListener 接口,也扩展了 EnvironmentLoader 类,应该是需要在 Servlet 容器中调用 EnvironmentLoader 对象的生命周期方法
从 Shiro 1.2 开始引入了 Environment/WebEnvironment 的概念,即由它们的实现提供相应的 SecurityManager 及其相应的依赖。ShiroFilter 会自动找到 Environment 然后获取相应的依赖。
通过 EnvironmentLoaderListener 来创建相应的 WebEnvironment,并自动绑定到 ServletContext,默认使用 IniWebEnvironment 实现。

EnvironmentLoader的功能:

当容器启动时,读取 web.xml 文件,从中获取 WebEnvironment 接口的实现类(默认是 IniWebEnvironment),初始化该实例,并将其加载到 ServletContext 中。
当容器关闭时,销毁 WebEnvironment 实例,并从 ServletContext 将其移除。
IniWebEnvironment的功能:

查找并加载 shiro.ini 配置文件,首先从自身成员变量里查找,然后从 web.xml 中查找,然后从 /WEB-INF 下查找,然后从 classpath 下查找,若均未找到,则直接报错。
当找到了 ini 配置文件后就开始解析,此时构造了一个 Bean 容器(相当于一个轻量级的 IOC 容器),最终的目标是为了创建 WebSecurityManager 对象与 FilterChainResolver 对象,创建过程使用了 Abstract Factory 模式
EnvironmentLoaderListener无非就是在容器启动时创建 WebEnvironment 对象,并由该对象来读取 Shiro 配置文件,创建WebSecurityManager(安全管理器)与 FilterChainResolver(过滤链解析器) 对象,在ShiroFilter中起到了重要作用。

ShiroFilter 是整个 Shiro 的入口点,用于拦截需要安全控制的请求进行处理。
因为它拦截了所有的请求,后面的 Authentication(认证)和Authorization(授权)都由ShiroFilter说了算

和Spring/SpringBoot整合以后,我们只需要注入ShiroFilter即可,ShiroFilter由ShiroFilterFactoryBean负责创建。所以注入ShiroFilterFactoryBean,由 ShiroFilterFactoryBean创建 ShiroFilter即可

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI