欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解spring與shiro集成

 更新時間:2017年09月25日 10:03:43   投稿:mrr  
這篇文章主要介紹了詳解spring與shiro集成,需要的朋友可以參考下

Shiro的組件都是JavaBean/POJO式的組件,所以非常容易使用Spring進行組件管理,可以非常方便的從ini配置遷移到Spring進行管理,且支持JavaSE應(yīng)用及Web應(yīng)用的集成。

在示例之前,需要導(dǎo)入shiro-spring及spring-context依賴,具體請參考pom.xml。

spring-beans.xml配置文件提供了基礎(chǔ)組件如DataSource、DAO、Service組件的配置。

JavaSE應(yīng)用 

spring-shiro.xml提供了普通JavaSE獨立應(yīng)用的Spring配置:

<!-- 緩存管理器 使用Ehcache實現(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實現(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> 
<!-- 會話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> 
<!-- 會話驗證調(diào)度器 --> 
<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> 
<!-- 相當(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配置方式即可,無須多解釋。LifecycleBeanPostProcessor用于在實現(xiàn)了Initializable接口的Shiro bean初始化時調(diào)用Initializable接口回調(diào),在實現(xiàn)了Destroyable接口的Shiro bean銷毀時調(diào)用 Destroyable接口回調(diào)。如UserRealm就實現(xiàn)了Initializable,而DefaultSecurityManager實現(xiàn)了Destroyable。具體可以查看它們的繼承關(guān)系。  

測試用例請參考com.github.zhangkaitao.shiro.chapter12.ShiroTest。  

Web應(yīng)用

Web應(yīng)用和普通JavaSE應(yīng)用的某些配置是類似的,此處只提供一些不一樣的配置,詳細配置可以參考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是用于生產(chǎn)Session ID Cookie的模板;

2、會話管理器使用用于web環(huán)境的DefaultWebSessionManager;

3、安全管理器使用用于web環(huán)境的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來創(chuàng)建ShiroFilter過濾器;filters屬性用于定義自己的過濾器,即ini配置中的[filters]部分;filterChainDefinitions用于聲明url和filter的關(guān)系,即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權(quán)限注解

Shiro提供了相應(yīng)的注解用于權(quán)限控制,如果使用這些注解就需要使用AOP的功能來進行判斷,如Spring AOP;Shiro提供了Spring AOP集成用于權(quán)限注解的解析和驗證。

為了測試,此處使用了Spring MVC來測試Shiro注解,當(dāng)然Shiro注解不僅僅可以在web環(huán)境使用,在獨立的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)中使用如下方式進行注解: 

@RequiresRoles("admin") 
@RequestMapping("/hello2") 
public String hello2() { 
  return "success"; 
} 

訪問hello2方法的前提是當(dāng)前用戶有admin角色。 

當(dāng)驗證失敗,其會拋出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; 
} 

 權(quán)限注解      

@RequiresAuthentication  

表示當(dāng)前Subject已經(jīng)通過login進行了身份驗證;即Subject. isAuthenticated()返回true。 

@RequiresUser  

表示當(dāng)前Subject已經(jīng)身份驗證或者通過記住我登錄的。

@RequiresGuest  

表示當(dāng)前Subject沒有身份驗證或通過記住我登錄過,即是游客身份。  

@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集成,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • SpringBoot 如何使用RestTemplate來調(diào)用接口

    SpringBoot 如何使用RestTemplate來調(diào)用接口

    這篇文章主要介紹了SpringBoot 如何使用RestTemplate來調(diào)用接口方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • java中阻塞隊列和非阻塞隊列的實現(xiàn)

    java中阻塞隊列和非阻塞隊列的實現(xiàn)

    在Java并發(fā)編程中,阻塞隊列和非阻塞隊列是兩種主要的隊列類型,分別適用于不同的場景,了解這兩種隊列的特點和工作機制,可以幫助開發(fā)者更好地選擇合適的數(shù)據(jù)結(jié)構(gòu)解決并發(fā)問題
    2024-10-10
  • Java中獲取List中最后一個元素的三種方法

    Java中獲取List中最后一個元素的三種方法

    在Java編程中我們經(jīng)常需要獲取一個List集合中的最后一個元素,這篇文章主要給大家介紹了關(guān)于Java中獲取List中最后一個元素的三種方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-12-12
  • Spring AI 使用本地 Ollama Embeddings的操作方法

    Spring AI 使用本地 Ollama Embeddings的操作方法

    使用 OpenAI 的 Embeddings 接口是有費用的,如果想對大量文檔進行測試,使用本地部署的 Embeddings 就能省去大量的費用,所以我們嘗試使用本地的 Ollama Embeddings,這篇文章主要介紹了Spring AI 使用本地 Ollama Embeddings,需要的朋友可以參考下
    2024-05-05
  • Java JVM原理與調(diào)優(yōu)_動力節(jié)點Java學(xué)院整理

    Java JVM原理與調(diào)優(yōu)_動力節(jié)點Java學(xué)院整理

    JVM是Java Virtual Machine(Java虛擬機)的縮寫,JVM是一種用于計算設(shè)備的規(guī)范,它是一個虛構(gòu)出來的計算機,是通過在實際的計算機上仿真模擬各種計算機功能來實現(xiàn)的。下面通過本文給大家介紹jvm原理與調(diào)優(yōu)相關(guān)知識,感興趣的朋友一起學(xué)習(xí)吧
    2017-04-04
  • Spring?cloud負載均衡@LoadBalanced?&?LoadBalancerClient

    Spring?cloud負載均衡@LoadBalanced?&?LoadBalancerClient

    由于Spring?cloud2020之后移除了Ribbon,直接使用Spring?Cloud?LoadBalancer作為客戶端負載均衡組件,我們討論Spring負載均衡以Spring?Cloud2020之后版本為主,學(xué)習(xí)Spring?Cloud?LoadBalance
    2023-11-11
  • SpringBoot項目在啟動后自動關(guān)閉的實現(xiàn)

    SpringBoot項目在啟動后自動關(guān)閉的實現(xiàn)

    我們在寫spring?boot?web項目時,有時會遇到啟動后立即關(guān)閉的情況,?本文主要介紹了SpringBoot項目在啟動后自動關(guān)閉的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • 關(guān)于SpringCloudStream配置問題

    關(guān)于SpringCloudStream配置問題

    這篇文章主要介紹了關(guān)于SpringCloudStream配置問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • springMVC?MultipartFile上傳圖片時如何修改圖片大小

    springMVC?MultipartFile上傳圖片時如何修改圖片大小

    這篇文章主要介紹了springMVC?MultipartFile上傳圖片時如何修改圖片大小問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Spring整合Mycat2的具體過程詳解

    Spring整合Mycat2的具體過程詳解

    這篇文章主要給大家介紹Springboot整合Mycat2的具體過程,文中有詳細的圖解過程,感興趣的小伙伴可以跟著小編一起來學(xué)習(xí)
    2023-05-05

最新評論