前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Shiro框架学习,Shiro与Spring集成

Shiro框架学习,Shiro与Spring集成

作者头像
用户1289394
发布于 2021-04-20 03:15:21
发布于 2021-04-20 03:15:21
68300
代码可运行
举报
文章被收录于专栏:Java学习网Java学习网
运行总次数:0
代码可运行

Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用Spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成。

在示例之前,需要导入shiro-spring及spring-context依赖,具体请参考pom.xml。

spring-beans.xml配置文件提供了基础组件如DataSource、DAO、Service组件的配置。

JavaSE应用

spring-shiro.xml提供了普通JavaSE独立应用的Spring配置:

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 缓存管理器 使用Ehcache实现 -->  
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>  
</bean>  
  
<!-- 凭证匹配器 -->  
<bean id="credentialsMatcher" class="  
com.github.zhangkaitao.shiro.chapter12.credentials.RetryLimitHashedCredentialsMatcher">  
    <constructor-arg ref="cacheManager"/>  
    <property name="hashAlgorithmName" value="md5"/>  
    <property name="hashIterations" value="2"/>  
    <property name="storedCredentialsHexEncoded" value="true"/>  
</bean>  
  
<!-- Realm实现 -->  
<bean id="userRealm" class="com.github.zhangkaitao.shiro.chapter12.realm.UserRealm">  
    <property name="userService" ref="userService"/>  
    <property name="credentialsMatcher" ref="credentialsMatcher"/>  
    <property name="cachingEnabled" value="true"/>  
    <property name="authenticationCachingEnabled" value="true"/>  
    <property name="authenticationCacheName" value="authenticationCache"/>  
    <property name="authorizationCachingEnabled" value="true"/>  
    <property name="authorizationCacheName" value="authorizationCache"/>  
</bean>  
<!-- 会话ID生成器 -->  
<bean id="sessionIdGenerator"   
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>  
<!-- 会话DAO -->  
<bean id="sessionDAO"   
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">  
    <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>  
    <property name="sessionIdGenerator" ref="sessionIdGenerator"/>  
</bean>  
<!-- 会话验证调度器 -->  
<bean id="sessionValidationScheduler"   
class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">  
    <property name="sessionValidationInterval" value="1800000"/>  
    <property name="sessionManager" ref="sessionManager"/>  
</bean>  
<!-- 会话管理器 -->  
<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">  
    <property name="globalSessionTimeout" value="1800000"/>  
    <property name="deleteInvalidSessions" value="true"/>  
    <property name="sessionValidationSchedulerEnabled" value="true"/>  
   <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>  
    <property name="sessionDAO" ref="sessionDAO"/>  
</bean>  
<!-- 安全管理器 -->  
<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">  
    <property name="realms">  
        <list><ref bean="userRealm"/></list>  
    </property>  
    <property name="sessionManager" ref="sessionManager"/>  
    <property name="cacheManager" ref="cacheManager"/>  
</bean>  
<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->  
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
<property name="staticMethod"   
value="org.apache.shiro.SecurityUtils.setSecurityManager"/>  
    <property name="arguments" ref="securityManager"/>  
</bean>  
<!-- Shiro生命周期处理器-->  
<bean id="lifecycleBeanPostProcessor"   
class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  

可以看出,只要把之前的ini配置翻译为此处的spring xml配置方式即可,无须多解释。LifecycleBeanPostProcessor用于在实现了Initializable接口的Shiro bean初始化时调用Initializable接口回调,在实现了Destroyable接口的Shiro bean销毁时调用 Destroyable接口回调。如UserRealm就实现了Initializable,而DefaultSecurityManager实现了Destroyable。具体可以查看它们的继承关系。

测试用例请参考com.github.zhangkaitao.shiro.chapter12.ShiroTest。

Web应用

Web应用和普通JavaSE应用的某些配置是类似的,此处只提供一些不一样的配置,详细配置可以参考spring-shiro-web.xml。

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 会话Cookie模板 -->  
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
    <constructor-arg value="sid"/>  
    <property name="httpOnly" value="true"/>  
    <property name="maxAge" value="180000"/>  
</bean>  
<!-- 会话管理器 -->  
<bean id="sessionManager"   
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
    <property name="globalSessionTimeout" value="1800000"/>  
    <property name="deleteInvalidSessions" value="true"/>  
    <property name="sessionValidationSchedulerEnabled" value="true"/>  
    <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>  
    <property name="sessionDAO" ref="sessionDAO"/>  
    <property name="sessionIdCookieEnabled" value="true"/>  
    <property name="sessionIdCookie" ref="sessionIdCookie"/>  
</bean>  
<!-- 安全管理器 -->  
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
<property name="realm" ref="userRealm"/>  
    <property name="sessionManager" ref="sessionManager"/>  
    <property name="cacheManager" ref="cacheManager"/>  
</bean>   

1、sessionIdCookie是用于生产Session ID Cookie的模板;

2、会话管理器使用用于web环境的DefaultWebSessionManager;

3、安全管理器使用用于web环境的DefaultWebSecurityManager。

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 基于Form表单的身份验证过滤器 -->  
<bean id="formAuthenticationFilter"   
class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">  
    <property name="usernameParam" value="username"/>  
    <property name="passwordParam" value="password"/>  
    <property name="loginUrl" value="/login.jsp"/>  
</bean>  
<!-- Shiro的Web过滤器 -->  
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
    <property name="securityManager" ref="securityManager"/>  
    <property name="loginUrl" value="/login.jsp"/>  
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/>  
    <property name="filters">  
        <util:map>  
            <entry key="authc" value-ref="formAuthenticationFilter"/>  
        </util:map>  
    </property>  
    <property name="filterChainDefinitions">  
        <value>  
            /index.jsp = anon  
            /unauthorized.jsp = anon  
            /login.jsp = authc  
            /logout = logout  
            /** = user  
        </value>  
    </property>  
</bean>   

1、formAuthenticationFilter为基于Form表单的身份验证过滤器;此处可以再添加自己的Filter bean定义;

2、shiroFilter:此处使用ShiroFilterFactoryBean来创建ShiroFilter过滤器;filters属性用于定义自己的过滤器,即ini配置中的[filters]部分;filterChainDefinitions用于声明url和filter的关系,即ini配置中的[urls]部分。

接着需要在web.xml中进行如下配置:

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        classpath:spring-beans.xml,  
        classpath:spring-shiro-web.xml  
    </param-value>  
</context-param>  
<listener>  
   <listener-class>  
org.springframework.web.context.ContextLoaderListener  
</listener-class>  
</listener>   

通过ContextLoaderListener加载contextConfigLocation指定的Spring配置文件。

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<filter>  
    <filter-name>shiroFilter</filter-name>  
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    <init-param>  
        <param-name>targetFilterLifecycle</param-name>  
        <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>shiroFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>   

DelegatingFilterProxy会自动到Spring容器中查找名字为shiroFilter的bean并把filter请求交给它处理。

其他配置请参考源代码。

Shiro权限注解

Shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用AOP的功能来进行判断,如Spring AOP;Shiro提供了Spring AOP集成用于权限注解的解析和验证。

为了测试,此处使用了Spring MVC来测试Shiro注解,当然Shiro注解不仅仅可以在web环境使用,在独立的JavaSE中也是可以用的,此处只是以web为例了。

在spring-mvc.xml配置文件添加Shiro Spring AOP权限注解的支持:

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<aop:config proxy-target-class="true"></aop:config>  
<bean class="  
org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
    <property name="securityManager" ref="securityManager"/>  
</bean>   

如上配置用于开启Shiro Spring AOP权限注解的支持;<aop:config proxy-target-class="true">表示代理类。

接着就可以在相应的控制器(AnnotationController)中使用如下方式进行注解:

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RequiresRoles("admin")  
@RequestMapping("/hello2")  
public String hello2() {  
    return "success";  
}   

访问hello2方法的前提是当前用户有admin角色。

当验证失败,其会抛出UnauthorizedException异常,此时可以使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@ExceptionHandler({UnauthorizedException.class})  
@ResponseStatus(HttpStatus.UNAUTHORIZED)  
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {  
    ModelAndView mv = new ModelAndView();  
    mv.addObject("exception", e);  
    mv.setViewName("unauthorized");  
    return mv;  
}   

如果集成Struts2,需要注意《Shiro+Struts2+Spring3 加上@RequiresPermissions 后@Autowired失效》问题:

http://jinnianshilongnian.iteye.com/blog/1850425

权限注解

Java代码

  1. @RequiresAuthentication

表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。

Java代码

  1. @RequiresUser

表示当前Subject已经身份验证或者通过记住我登录的。

Java代码

  1. @RequiresGuest

表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)  

表示当前Subject需要角色admin和user。

Java代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)  

表示当前Subject需要权限user:a或user:b。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java学习网 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
shiro和spring整合
之前用shiro参考官网写了简单的示例,对于shiro我们大致可以了解其主要的构造,网上有很多这样的示例,但是对于开发者来说,我们需要做的很少,可以说大部分模块都已经由框架本身帮助我们实现,我们需要关注的仅仅是框架开放且无法实现的模块,即验证模型构建,而java基本都是以面向接口未核心,那么我只需要完成核心接口的实现即可。
sucl
2019/08/07
7110
第八章:Shiro和Spring的集成——深入浅出学Shiro细粒度权限开发框架
Standalone Applications
MonroeCode
2018/01/10
6230
spring shiro权限控制_shiro权限管理流程
大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说spring shiro权限控制_shiro权限管理流程,希望能够帮助大家进步!!!
Java架构师必看
2022/08/14
1.9K0
spring shiro权限控制_shiro权限管理流程
从权限控制到shiro框架的应用
说明:本文很多观点和内容来自互联网以及各种资料,如果侵犯了您的权益,请及时联系我,我会删除相关内容。 权限管理 基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己被授权的资源。 权限管理包括用户身份认证和授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问权限方可访问。 用户身份认证 身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简
神秘的寇先森
2018/05/30
2.4K0
shiro框架—shiro配置介绍(一)
接上一篇文章shiro框架—通过系统介绍shiro框架中的实现逻辑   项目已分享到GitHub上,如果需要的可以看下,springboot+shiro项目Git下载地址。
全栈程序员站长
2022/10/04
1.3K0
shiro框架—shiro配置介绍(一)
shiro权限管理框架与springmvc整合
shiro是apache下的一个项目,和spring security类似,用于用户权限的管理‘
肖哥哥
2019/02/22
5750
shiro权限管理框架与springmvc整合
shiro用的好的话抗住千万流量没问题!自定义过滤器鉴权|Java 开发实战
Shiros是我们开发中常用的用来实现权限控制的一种工具包,它主要有认证、授权、加密、会话管理、与Web集成、缓存等功能。我是从事javaweb工作的,我就经常遇到需要实现权限控制的项目,之前我们都是靠查询数据获取列表拼接展示的,还有的是及时的判断权限的问题的,现在有了Shiros了,我们就可以统一的进行设置权限问题,Shrios的实现也是很简单的,下面让我们来看看具体实现步骤
啵啵肠
2023/11/28
3220
记一下Shiro重构之ShiroConfig配置文件
程序员朱永胜
2023/08/17
5190
shiro框架04会话管理+缓存管理+Ehcache使用
2)实现spring与ehcache缓存(创建spring-ehcache.xml)
天蝎座的程序媛
2022/11/18
1K0
shiro框架04会话管理+缓存管理+Ehcache使用
Shiro第三篇【授权过滤器、与ehcache整合、验证码、记住我】
前言 本文主要讲解的知识点有以下: Shiro授权过滤器使用 Shiro缓存 与Ehcache整合 Shiro应用->实现验证码功能 记住我功能 一、授权过滤器测试 我们的授权过滤器使用的是permissionsAuthorizationFilter来进行拦截。我们可以在application-shiro中配置filter规则 <!--商品查询需要商品查询权限 --> /items/queryItems.action = perms[item:query] /
Java3y
2018/04/02
2K0
Shiro第三篇【授权过滤器、与ehcache整合、验证码、记住我】
jeesite集成cas认证[通俗易懂]
cas和shiro集成,很好的解决了登录及权限问题。本人最近第一次使用,框架使用的是jeesite开源框架,本身已经集成了shiro,现在将cas集成到项目中。
全栈程序员站长
2022/07/02
7981
Shiro的原理及Web搭建
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
Java团长
2018/10/18
8410
Shiro的原理及Web搭建
shiro 和 spring boot 的集成
使用 shiro-spring-boot-web-starter 在 spring boot 中集成 shiro 只需要再添加一个依赖
Carlos Ouyang
2019/08/19
1.9K0
shiro 和 spring boot 的集成
shiro——会话管理
Shiro提供SessionDAO用于会话的CRUD,即DAO(Data Access Object)模式实现。
用户10196776
2022/11/22
1.1K0
shiro——会话管理
Shiro框架学习,Shiro并发登录人数控制
在某些项目中可能会遇到如每个账户同时只能有一个人登录或几个人同时登录,如果同时有多人登录:要么不让后者登录;要么踢出前者登录(强制退出)。比如spring security就直接提供了相应的功能;Shiro的话没有提供默认实现,不过可以很容易的在Shiro中加入这个功能。
用户1289394
2021/04/20
8980
Shiro框架学习,Shiro并发登录人数控制
Shiro框架学习,Shiro缓存机制
Shiro还提供了CacheManagerAware用于注入CacheManager:
用户1289394
2021/04/20
5680
Shiro框架学习,Shiro缓存机制
apache shiro 在spring 的使用
 <!-- SECURITY begin -->         <dependency>             <groupId>org.apache.shiro</groupId>             <artifactId>shiro-core</artifactId>             <version>${shiro.version}</version>         </dependency>         <dependency>             <groupId>org.apache.shiro</groupId>             <artifactId>shiro-spring</artifactId>             <version>${shiro.version}</version>         </dependency>         <dependency>             <groupId>org.apache.shiro</groupId>             <artifactId>shiro-cas</artifactId>             <version>${shiro.version}</version>             <exclusions>                 <exclusion>                     <groupId>commons-logging</groupId>                     <artifactId>commons-logging</artifactId>                 </exclusion>             </exclusions>         </dependency>         <dependency>             <groupId>org.apache.shiro</groupId>             <artifactId>shiro-web</artifactId>             <version>${shiro.version}</version>         </dependency>         <dependency>             <groupId>org.apache.shiro</groupId>             <artifactId>shiro-ehcache</artifactId>             <version>${shiro.version}</version>         </dependency>         <!-- SECURITY end -->
爱明依
2019/03/12
5880
Shiro 配置
Shiro的demo能够体验根据配置文件,达到是否能够登陆的效果,除此之外,Shiro整合Spring来达到实际使用场景。
疯狂的KK
2020/02/19
6630
Shiro集成应用 原
       Shiro项目始于2003年初,当时它叫JSecurity项目,当时对于Java应用开发人员没有太多的安全替代方案,始终被一个叫JAAS(Java认证/授权服务)束缚着,但是JAAS缺点太多了,如它的授权机制太拙劣,用起来让人沮丧,又一方面JAAS跟虚拟机层面的安全问题关系非常紧密,如判断JVM中判断是否允许装入一个类等,还有加密问题,JAVA中的密码架构又是让人难以理解。于是Jsecurity就诞生了,后来更名为Shiro。
wuweixiang
2018/08/14
5310
Shiro集成应用
                                                                            原
Shiro 整合 Spring 第一次
4.1 在applicationContext-shiro.xml文件中配置 凭证匹配器
用户5927264
2019/07/31
3230
相关推荐
shiro和spring整合
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验