详解spring与shiro集成
发布时间 - 2026-01-11 03:23:53 点击率:次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配置:
<!-- 缓存管理器 使用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。
<!-- 会话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。
<!-- 基于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中进行如下配置:
<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配置文件。
<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权限注解的支持:
<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)中使用如下方式进行注解:
@RequiresRoles("admin")
@RequestMapping("/hello2")
public String hello2() {
return "success";
}
访问hello2方法的前提是当前用户有admin角色。
当验证失败,其会抛出UnauthorizedException异常,此时可以使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:
@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;
}
权限注解
@RequiresAuthentication
表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。
@RequiresUser
表示当前Subject已经身份验证或者通过记住我登录的。
@RequiresGuest
表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)
表示当前Subject需要角色admin和user。
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)
表示当前Subject需要权限user:a或user:b。
总结
以上所述是小编给大家介绍的详解spring与shiro集成,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
# spring与shiro集成
# spring boot 1.5.4 集成shiro+cas
# 实现单点登录和权限控制
# SpringBoot集成Shiro进行权限控制和管理的示例
# springmvc集成shiro登录权限示例代码
# spring boot集成shiro详细教程(小结)
# 详解Spring Boot 集成Shiro和CAS
# spring boot 集成shiro的配置方法
# Spring Boot集成Shiro并利用MongoDB做Session存储的方法详解
# shiro无状态web集成的示例代码
# Spring 应用中集成 Apache Shiro的方法
# Shiro集成Spring之注解示例详解
# 管理器
# 身份验证
# 自己的
# 实现了
# 配置文件
# 表单
# 回调
# 小编
# 请参考
# 记住我
# 都是
# 在此
# 可以用
# 要把
# 给大家
# 可以使用
# 为例
# 可以看出
# 即是
# 只提供
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
宙斯浏览器怎么屏蔽图片浏览 节省手机流量使用设置方法
JS实现鼠标移上去显示图片或微信二维码
Linux系统运维自动化项目教程_Ansible批量管理实战
LinuxCD持续部署教程_自动发布与回滚机制
Laravel如何获取当前用户信息_Laravel Auth门面获取用户ID
成都品牌网站制作公司,成都营业执照年报网上怎么办理?
Laravel怎么调用外部API_Laravel Http Client客户端使用
猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?
如何快速打造个性化非模板自助建站?
php中::能调用final静态方法吗_final修饰静态方法调用规则【解答】
Laravel如何实现本地化和多语言支持_Laravel多语言配置与翻译文件管理
黑客入侵网站服务器的常见手法有哪些?
高性能网站服务器部署指南:稳定运行与安全配置优化方案
bootstrap日历插件datetimepicker使用方法
Windows Hello人脸识别突然无法使用
Laravel API资源(Resource)怎么用_格式化Laravel API响应的最佳实践
悟空识字怎么关闭自动续费_悟空识字取消会员自动扣费步骤
ChatGPT常用指令模板大全 新手快速上手的万能Prompt合集
手机网站制作与建设方案,手机网站如何建设?
如何在宝塔面板创建新站点?
米侠浏览器网页图片不显示怎么办 米侠图片加载修复
QQ浏览器网页版登录入口 个人中心在线进入
Java Adapter 适配器模式(类适配器,对象适配器)优缺点对比
如何在万网ECS上快速搭建专属网站?
如何在IIS7中新建站点?详细步骤解析
laravel怎么在请求结束后执行任务(Terminable Middleware)_laravel Terminable Middleware请求结束任务执行方法
Laravel如何从数据库删除数据_Laravel destroy和delete方法区别
Laravel Asset编译怎么配置_Laravel Vite前端构建工具使用
原生JS获取元素集合的子元素宽度实例
javascript如何操作浏览器历史记录_怎样实现无刷新导航
iOS中将个别页面强制横屏其他页面竖屏
今日头条AI怎样推荐抢票工具_今日头条AI抢票工具推荐算法与筛选【技巧】
悟空浏览器如何设置小说背景色_悟空浏览器背景色设置【方法】
Laravel怎么使用Markdown渲染文档_Laravel将Markdown内容转HTML页面展示【实战】
手机软键盘弹出时影响布局的解决方法
零服务器AI建站解决方案:快速部署与云端平台低成本实践
详解Huffman编码算法之Java实现
如何打造高效商业网站?建站目的决定转化率
详解Nginx + Tomcat 反向代理 负载均衡 集群 部署指南
详解Android图表 MPAndroidChart折线图
jquery插件bootstrapValidator表单验证详解
iOS正则表达式验证手机号、邮箱、身份证号等
如何在云主机上快速搭建网站?
Laravel Eloquent:优雅地将关联模型字段扁平化到主模型中
实例解析angularjs的filter过滤器
Android自定义控件实现温度旋转按钮效果
如何快速生成专业多端适配建站电话?
什么是javascript作用域_全局和局部作用域有什么区别?
HTML 中动态设置元素 name 属性的正确语法详解
谷歌浏览器如何更改浏览器主题 Google Chrome主题设置教程

