SpringMVC整合Shiro


摘要: SpringMVC整合Shiro,Shiro是一個強大易用的Java安全框架,提供了認證、授權、加密和會話管理等功能。

第一步:配置web.xml

     
     
     
             
  1. <!-- 配置Shiro過濾器,先讓Shiro過濾系統接收到的請求 -->
  2. <!-- 這里filter-name必須對應applicationContext.xml中定義的<bean id="shiroFilter"/> -->
  3. <!-- 使用[/*]匹配所有請求,保證所有的可控請求都經過Shiro的過濾 -->
  4. <!-- 通常會將此filter-mapping放置到最前面(即其他filter-mapping前面),以保證它是過濾器鏈中第一個起作用的 -->
  5. <filter>
  6. <filter-name>shiroFilter</filter-name>
  7. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  8. <init-param>
  9. <!-- 該值缺省為false,表示生命周期由SpringApplicationContext管理,設置為true則表示由ServletContainer管理 -->
  10. <param-name>targetFilterLifecycle</param-name>
  11. <param-value>true</param-value>
  12. </init-param>
  13. </filter>
  14. <filter-mapping>
  15. <filter-name>shiroFilter</filter-name>
  16. <url-pattern>/*</url-pattern>
  17. </filter-mapping>

第二步:配置applicationContext.xml
       
       
       
               
  1. <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類為自定義的ShiroDbRealm.java -->  
  2. <bean id="myRealm" class="com.jadyer.realm.MyRealm"/>  
  3.   
  4. <!-- Shiro默認會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session -->  
  5. <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 -->  
  6. <!-- 這里主要是設置自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 -->  
  7. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  8.     <property name="realm" ref="myRealm"/>  
  9. </bean>  
  10.   
  11. <!-- Shiro主過濾器本身功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行 -->  
  12. <!-- Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支持 -->  
  13. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  14.     <!-- Shiro的核心安全接口,這個屬性是必須的 -->  
  15.     <property name="securityManager" ref="securityManager"/>  
  16.     <!-- 要求登錄時的鏈接(可根據項目的URL進行替換),非必須的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->  
  17.     <property name="loginUrl" value="/"/>  
  18.     <!-- 登錄成功后要跳轉的連接(本例中此屬性用不到,因為登錄成功后的處理邏輯在LoginController里硬編碼為main.jsp了) -->  
  19.     <!-- <property name="successUrl" value="/system/main"/> -->  
  20.     <!-- 用戶訪問未對其授權的資源時,所顯示的連接 -->  
  21.     <!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然后用[玄玉]登錄后訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp -->  
  22.     <property name="unauthorizedUrl" value="/"/>  
  23.     <!-- Shiro連接約束配置,即過濾鏈的定義 -->  
  24.     <!-- 此處可配合我的這篇文章來理解各個過濾連的作用http://blog.csdn.net/jadyer/article/details/12172839 -->  
  25.     <!-- 下面value值的第一個'/'代表的路徑是相對於HttpServletRequest.getContextPath()的值來的 -->  
  26.     <!-- anon:它對應的過濾器里面是空的,什么都沒做,這里.do和.jsp后面的*表示參數,比方說login.jsp?main這種 -->  
  27.     <!-- authc:該過濾器下的頁面必須驗證后才能訪問,它是Shiro內置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->  
  28.     <property name="filterChainDefinitions">  
  29.         <value>  
  30.              /mydemo/login=anon  
  31.              /mydemo/getVerifyCodeImage=anon  
  32.              /main**=authc  
  33.              /user/info**=authc  
  34.              /admin/listUser**=authc,perms[admin:manage]  
  35.         </value>  
  36.     </property>
  37. </bean>  
  38.   
  39. <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->  
  40. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
  41.   
  42. <!-- 開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,並在必要時進行安全邏輯驗證 -->  
  43. <!-- 配置以下兩個bean即可實現此功能 -->  
  44. <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->  
  45. <!-- 由於本例中並未使用Shiro注解,故注釋掉這兩個bean(個人覺得將權限通過注解的方式硬編碼在程序中,查看起來不是很方便,沒必要使用) -->  
  46. <!--   
  47. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>  
  48.   <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  49.     <property name="securityManager" ref="securityManager"/>  
  50.   </bean>  
  51. -->

第三步:自定義的Realm類
         
         
         
                 
  1. public class MyRealm extends AuthorizingRealm {  
  2.     /** 
  3.      * 為當前登錄的Subject授予角色和權限 
  4.      * @see  經測試:本例中該方法的調用時機為需授權資源被訪問時 
  5.      * @see  經測試:並且每次訪問需授權資源時都會執行該方法中的邏輯,這表明本例中默認並未啟用AuthorizationCache 
  6.      * @see  個人感覺若使用了Spring3.1開始提供的ConcurrentMapCache支持,則可靈活決定是否啟用AuthorizationCache 
  7.      * @see  比如說這里從數據庫獲取權限信息時,先去訪問Spring3.1提供的緩存,而不使用Shior提供的AuthorizationCache 
  8.      */  
  9.     @Override  
  10.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
  11.         //獲取當前登錄的用戶名,等價於(String)principals.fromRealm(this.getName()).iterator().next()  
  12.         String currentUsername = (String)super.getAvailablePrincipal(principals);  
  13. //      List<String> roleList = new ArrayList<String>();  
  14. //      List<String> permissionList = new ArrayList<String>();  
  15. //      //從數據庫中獲取當前登錄用戶的詳細信息  
  16. //      User user = userService.getByUsername(currentUsername);  
  17. //      if(null != user){  
  18. //          //實體類User中包含有用戶角色的實體類信息  
  19. //          if(null!=user.getRoles() && user.getRoles().size()>0){  
  20. //              //獲取當前登錄用戶的角色  
  21. //              for(Role role : user.getRoles()){  
  22. //                  roleList.add(role.getName());  
  23. //                  //實體類Role中包含有角色權限的實體類信息  
  24. //                  if(null!=role.getPermissions() && role.getPermissions().size()>0){  
  25. //                      //獲取權限  
  26. //                      for(Permission pmss : role.getPermissions()){  
  27. //                          if(!StringUtils.isEmpty(pmss.getPermission())){  
  28. //                              permissionList.add(pmss.getPermission());  
  29. //                          }  
  30. //                      }  
  31. //                  }  
  32. //              }  
  33. //          }  
  34. //      }else{  
  35. //          throw new AuthorizationException();  
  36. //      }  
  37. //      //為當前用戶設置角色和權限  
  38. //      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
  39. //      simpleAuthorInfo.addRoles(roleList);  
  40. //      simpleAuthorInfo.addStringPermissions(permissionList);  
  41.         SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
  42.         //實際中可能會像上面注釋的那樣從數據庫取得  
  43.         if(null!=currentUsername && "mike".equals(currentUsername)){  
  44.             //添加一個角色,不是配置意義上的添加,而是證明該用戶擁有admin角色    
  45.             simpleAuthorInfo.addRole("admin");  
  46.             //添加權限  
  47.             simpleAuthorInfo.addStringPermission("admin:manage");  
  48.             System.out.println("已為用戶[mike]賦予了[admin]角色和[admin:manage]權限");  
  49.             return simpleAuthorInfo;  
  50.         }
  51.         //若該方法什么都不做直接返回null的話,就會導致任何用戶訪問/admin/listUser.jsp時都會自動跳轉到unauthorizedUrl指定的地址  
  52.         //詳見applicationContext.xml中的<bean id="shiroFilter">的配置  
  53.         return null;  
  54.     }  
  55.   
  56.       
  57.     /** 
  58.      * 驗證當前登錄的Subject 
  59.      * @see  經測試:本例中該方法的調用時機為LoginController.login()方法中執行Subject.login()時 
  60.      */  
  61.     @Override  
  62.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
  63.         //獲取基於用戶名和密碼的令牌  
  64.         //實際上這個authcToken是從LoginController里面currentUser.login(token)傳過來的  
  65.         //兩個token的引用都是一樣的
  66.         UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
  67.         System.out.println("驗證當前Subject時獲取到token為" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
  68. //      User user = userService.getByUsername(token.getUsername());  
  69. //      if(null != user){  
  70. //          AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname());  
  71. //          this.setSession("currentUser", user);  
  72. //          return authcInfo;  
  73. //      }else{  
  74. //          return null;  
  75. //      }  
  76.         //此處無需比對,比對的邏輯Shiro會做,我們只需返回一個和令牌相關的正確的驗證信息  
  77.         //說白了就是第一個參數填登錄用戶名,第二個參數填合法的登錄密碼(可以是從數據庫中取到的,本例中為了演示就硬編碼了)  
  78.         //這樣一來,在隨后的登錄頁面上就只有這里指定的用戶和密碼才能通過驗證  
  79.         if("mike".equals(token.getUsername())){  
  80.             AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("mike", "mike", this.getName());  
  81.             this.setSession("currentUser", "mike");  
  82.             return authcInfo;  
  83.         }
  84.         //沒有返回登錄用戶名對應的SimpleAuthenticationInfo對象時,就會在LoginController中拋出UnknownAccountException異常  
  85.         return null;  
  86.     }  
  87.       
  88.       
  89.     /** 
  90.      * 將一些數據放到ShiroSession中,以便於其它地方使用 
  91.      * @see  比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到 
  92.      */  
  93.     private void setSession(Object key, Object value){  
  94.         Subject currentUser = SecurityUtils.getSubject();  
  95.         if(null != currentUser){  
  96.             Session session = currentUser.getSession();  
  97.             System.out.println("Session默認超時時間為[" + session.getTimeout() + "]毫秒");  
  98.             if(null != session){  
  99.                 session.setAttribute(key, value);  
  100.             }  
  101.         }  
  102.     }  
  103. }







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM