詳解spring與shiro集成
Shiro的組件都是JavaBean/POJO式的組件,所以非常容易使用Spring進(jìn)行組件管理,可以非常方便的從ini配置遷移到Spring進(jìn)行管理,且支持JavaSE應(yīng)用及Web應(yīng)用的集成。
在示例之前,需要導(dǎo)入shiro-spring及spring-context依賴,具體請(qǐng)參考pom.xml。
spring-beans.xml配置文件提供了基礎(chǔ)組件如DataSource、DAO、Service組件的配置。
JavaSE應(yīng)用
spring-shiro.xml提供了普通JavaSE獨(dú)立應(yīng)用的Spring配置:
<!-- 緩存管理器 使用Ehcache實(shí)現(xiàn) -->
<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實(shí)現(xiàn) -->
<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>
<!-- 會(huì)話ID生成器 -->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
<!-- 會(huì)話DAO -->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
<property name="sessionIdGenerator" ref="sessionIdGenerator"/>
</bean>
<!-- 會(huì)話驗(yàn)證調(diào)度器 -->
<bean id="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
<property name="sessionValidationInterval" value="1800000"/>
<property name="sessionManager" ref="sessionManager"/>
</bean>
<!-- 會(huì)話管理器 -->
<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>
<!-- 相當(dāng)于調(diào)用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配置方式即可,無(wú)須多解釋。LifecycleBeanPostProcessor用于在實(shí)現(xiàn)了Initializable接口的Shiro bean初始化時(shí)調(diào)用Initializable接口回調(diào),在實(shí)現(xiàn)了Destroyable接口的Shiro bean銷毀時(shí)調(diào)用 Destroyable接口回調(diào)。如UserRealm就實(shí)現(xiàn)了Initializable,而DefaultSecurityManager實(shí)現(xiàn)了Destroyable。具體可以查看它們的繼承關(guān)系。
測(cè)試用例請(qǐng)參考com.github.zhangkaitao.shiro.chapter12.ShiroTest。
Web應(yīng)用
Web應(yīng)用和普通JavaSE應(yīng)用的某些配置是類似的,此處只提供一些不一樣的配置,詳細(xì)配置可以參考spring-shiro-web.xml。
<!-- 會(huì)話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> <!-- 會(huì)話管理器 --> <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是用于生產(chǎn)Session ID Cookie的模板;
2、會(huì)話管理器使用用于web環(huán)境的DefaultWebSessionManager;
3、安全管理器使用用于web環(huán)境的DefaultWebSecurityManager。
<!-- 基于Form表單的身份驗(yàn)證過(guò)濾器 -->
<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過(guò)濾器 -->
<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表單的身份驗(yàn)證過(guò)濾器;此處可以再添加自己的Filter bean定義;
2、shiroFilter:此處使用ShiroFilterFactoryBean來(lái)創(chuàng)建ShiroFilter過(guò)濾器;filters屬性用于定義自己的過(guò)濾器,即ini配置中的[filters]部分;filterChainDefinitions用于聲明url和filter的關(guān)系,即ini配置中的[urls]部分。
接著需要在web.xml中進(jìn)行如下配置:
<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>
通過(guò)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會(huì)自動(dòng)到Spring容器中查找名字為shiroFilter的bean并把filter請(qǐng)求交給它處理。
Shiro權(quán)限注解
Shiro提供了相應(yīng)的注解用于權(quán)限控制,如果使用這些注解就需要使用AOP的功能來(lái)進(jìn)行判斷,如Spring AOP;Shiro提供了Spring AOP集成用于權(quán)限注解的解析和驗(yàn)證。
為了測(cè)試,此處使用了Spring MVC來(lái)測(cè)試Shiro注解,當(dāng)然Shiro注解不僅僅可以在web環(huán)境使用,在獨(dú)立的JavaSE中也是可以用的,此處只是以web為例了。
在spring-mvc.xml配置文件添加Shiro Spring AOP權(quán)限注解的支持:
<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權(quán)限注解的支持;<aop:config proxy-target-class="true">表示代理類。
接著就可以在相應(yīng)的控制器(AnnotationController)中使用如下方式進(jìn)行注解:
@RequiresRoles("admin")
@RequestMapping("/hello2")
public String hello2() {
return "success";
}
訪問(wèn)hello2方法的前提是當(dāng)前用戶有admin角色。
當(dāng)驗(yàn)證失敗,其會(huì)拋出UnauthorizedException異常,此時(shí)可以使用Spring的ExceptionHandler(DefaultExceptionHandler)來(lái)進(jìn)行攔截處理:
@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;
}
權(quán)限注解
@RequiresAuthentication
表示當(dāng)前Subject已經(jīng)通過(guò)login進(jìn)行了身份驗(yàn)證;即Subject. isAuthenticated()返回true。
@RequiresUser
表示當(dāng)前Subject已經(jīng)身份驗(yàn)證或者通過(guò)記住我登錄的。
@RequiresGuest
表示當(dāng)前Subject沒(méi)有身份驗(yàn)證或通過(guò)記住我登錄過(guò),即是游客身份。
@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)
表示當(dāng)前Subject需要角色admin和user。
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)
表示當(dāng)前Subject需要權(quán)限user:a或user:b。
總結(jié)
以上所述是小編給大家介紹的詳解spring與shiro集成,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- spring boot 1.5.4 集成shiro+cas,實(shí)現(xiàn)單點(diǎn)登錄和權(quán)限控制
- SpringBoot集成Shiro進(jìn)行權(quán)限控制和管理的示例
- springmvc集成shiro登錄權(quán)限示例代碼
- spring boot集成shiro詳細(xì)教程(小結(jié))
- 詳解Spring Boot 集成Shiro和CAS
- spring boot 集成shiro的配置方法
- Spring Boot集成Shiro并利用MongoDB做Session存儲(chǔ)的方法詳解
- shiro無(wú)狀態(tài)web集成的示例代碼
- Spring 應(yīng)用中集成 Apache Shiro的方法
- Shiro集成Spring之注解示例詳解
相關(guān)文章
Java中的Comparable接口與Comparator接口區(qū)別解析
文章介紹了Java中的Comparable接口和Comparator接口,Comparable接口定義了一個(gè)compareTo方法,用于比較對(duì)象的順序,實(shí)現(xiàn)Comparable接口的類可以提供自然排序規(guī)則,詳細(xì)介紹了Java中的Comparable接口與Comparator接口區(qū)別,感興趣的朋友一起看看吧2025-02-02
Java線程間通信不同步問(wèn)題原理與模擬實(shí)例
這篇文章主要介紹了Java線程間通信不同步問(wèn)題,結(jié)合實(shí)例形式分析了java線程間通信不同步問(wèn)題的原理并模擬實(shí)現(xiàn)了線程間通信不同步情況下的異常輸出,需要的朋友可以參考下2019-10-10
java根據(jù)圖片中綠色像素點(diǎn)的多少進(jìn)行排序
這篇文章主要介紹了java根據(jù)圖片中綠色像素點(diǎn)的多少進(jìn)行排序,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Mybatis配置之<environments>配置元素詳解
這篇文章主要介紹了Mybatis配置之<environments>配置元素,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
java簡(jiǎn)單實(shí)現(xiàn)復(fù)制 粘貼 剪切功能代碼分享
本文給大家分享了一段java編寫的簡(jiǎn)單實(shí)現(xiàn)復(fù)制粘貼剪切功能的代碼,需要的小伙伴可以直接拿走使用。如有更好的方案,也可以告之本人。2014-11-11
java實(shí)戰(zhàn)案例之用戶注冊(cè)并發(fā)送郵件激活/發(fā)送郵件驗(yàn)證碼
現(xiàn)在很多的網(wǎng)站都提供有用戶注冊(cè)功能,當(dāng)我們注冊(cè)成功之后就會(huì)收到封注冊(cè)網(wǎng)站的郵件,郵件里包含了我們的注冊(cè)的用戶名和密碼及激活賬戶的超鏈接等信息,這篇文章主要給大家介紹了關(guān)于java實(shí)戰(zhàn)案例之用戶注冊(cè)并發(fā)送郵件激活/發(fā)送郵件驗(yàn)證碼的相關(guān)資料,需要的朋友可以參考下2021-09-09
SpringCloud中的Ribbon負(fù)載均衡詳細(xì)解讀
這篇文章主要介紹了SpringCloud中的Ribbon負(fù)載均衡詳細(xì)解讀,當(dāng)系統(tǒng)面臨大量的用戶訪問(wèn),負(fù)載過(guò)高的時(shí)候,通常會(huì)增加服務(wù)器數(shù)量來(lái)進(jìn)行橫向擴(kuò)展(集群),多個(gè)服務(wù)器的負(fù)載需要均衡,以免出現(xiàn)服務(wù)器負(fù)載不均衡,部分服務(wù)器負(fù)載較大,部分服務(wù)器負(fù)載較小的情況,需要的朋友可以參考下2023-11-11
Java 并發(fā)編程ArrayBlockingQueue的實(shí)現(xiàn)
這篇文章主要介紹了Java 并發(fā)編程ArrayBlockingQueue的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02

