spring shiro

shiro是一款java安全框架、簡單而且可以滿足實際的工作需要

第一步、導入maven依賴  

Java代碼  收藏代碼
  1. <!-- shiro -->  
  2. <dependency>  
  3.     <groupId>org.apache.shiro</groupId>  
  4.     <artifactId>shiro-core</artifactId>  
  5.     <version>${org.apache.shiro.version}</version>  
  6. </dependency>  
  7. <dependency>  
  8.     <groupId>org.apache.shiro</groupId>  
  9.     <artifactId>shiro-web</artifactId>  
  10.     <version>${org.apache.shiro.version}</version>  
  11. </dependency>  
  12. <dependency>  
  13.     <groupId>org.apache.shiro</groupId>  
  14.     <artifactId>shiro-spring</artifactId>  
  15.     <version>${org.apache.shiro.version}</version>  
  16. </dependency>  
  17. <dependency>  
  18.     <groupId>org.apache.shiro</groupId>  
  19.     <artifactId>shiro-ehcache</artifactId>  
  20.     <version>${org.apache.shiro.version}</version>  
  21. </dependency>  

 第二步、在項目中定義shiro的過濾器(shiro的實現主要是通過filter實現)

Java代碼  收藏代碼
  1. <!-- Shiro Security filter -->  
  2. <filter>  
  3.     <filter-name>shiroFilter</filter-name>  
  4.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  5.     <init-param>  
  6.     <param-name>targetFilterLifecycle</param-name>  
  7.     <param-value>true</param-value>  
  8.     </init-param>  
  9. </filter>  
  10. <filter-mapping>  
  11.     <filter-name>shiroFilter</filter-name>  
  12.     <url-pattern>/*</url-pattern>  
  13.     <dispatcher>REQUEST</dispatcher>  
  14. </filter-mapping>  

 第三步、創建一個Realm

Java代碼  收藏代碼
  1. public class UserRealm extends AuthorizingRealm {  
  2.     @Autowired  
  3.     private UserBiz biz;  
  4.     //驗證用戶信息,認證的實現  
  5.     @Override  
  6.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {  
  7.         String userno = (String) authenticationToken.getPrincipal();  
  8.         String password = new String((char[]) authenticationToken.getCredentials());  
  9.         Result<RcUser> result = biz.login(userno, password);  
  10.         if (result.isStatus()) {  
  11.             Session session = SecurityUtils.getSubject().getSession();  
  12.             session.setAttribute(Constants.Token.RONCOO, userno);  
  13.             RcUser user = result.getResultData();  
  14.             return new SimpleAuthenticationInfo(user.getUserNo(), user.getPassword(), getName());  
  15.         }  
  16.         return null;  
  17.     }  
  18.     //驗證用戶的權限,實現認證  
  19.     @Override  
  20.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  21.         SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
  22.         String userno = (String) principals.getPrimaryPrincipal();  
  23.         Result<RcUser> result = biz.queryByUserNo(userno);  
  24.         if(result.isStatus()){  
  25.             Result<List<RcRole>> resultRole = biz.queryRoles(result.getResultData().getId());  
  26.             if(resultRole.isStatus()){  
  27.                 //獲取角色  
  28.                 HashSet<String> roles = new HashSet<String>();  
  29.                 for (RcRole rcRole : resultRole.getResultData()) {  
  30.                     roles.add(rcRole.getRoleValue());  
  31.                 }  
  32.                 System.out.println("角色:"+roles);  
  33.                 authorizationInfo.setRoles(roles);  
  34.                 //獲取權限  
  35.                 Result<List<RcPermission>> resultPermission = biz.queryPermissions(resultRole.getResultData());  
  36.                 if(resultPermission.isStatus()){  
  37.                     HashSet<String> permissions = new HashSet<String>();  
  38.                     for (RcPermission rcPermission : resultPermission.getResultData()) {  
  39.                         permissions.add(rcPermission.getPermissionsValue());  
  40.                     }  
  41.                     System.out.println("權限:"+permissions);  
  42.                     authorizationInfo.setStringPermissions(permissions);  
  43.                 }  
  44.             }  
  45.         }  
  46.         return authorizationInfo;  
  47.     }  
  48. }  

 第四步、添加shiro配置

Java代碼  收藏代碼
  1. 1、shiro緩存  
  2. <?xml version="1.0" encoding="UTF-8"?>  
  3. <!DOCTYPE xml>  
  4. <ehcache updateCheck="false" name="shiroCache">  
  5.     <!-- http://ehcache.org/ehcache.xml -->  
  6.     <defaultCache  
  7.             maxElementsInMemory="10000"  
  8.             eternal="false"  
  9.             timeToIdleSeconds="120"  
  10.             timeToLiveSeconds="120"  
  11.             overflowToDisk="false"  
  12.             diskPersistent="false"  
  13.             diskExpiryThreadIntervalSeconds="120"  
  14.             />  
  15. </ehcache>  
  16.   
  17. 2、在spring的core配置文件中配置shiro  
  18. <description>Shiro安全配置</description>  
  19.   
  20.     <bean id="userRealm" class="com.roncoo.adminlte.controller.realm.UserRealm" />   
  21.   
  22.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  23.         <property name="realm" ref="userRealm" />  
  24.         <property name="cacheManager" ref="shiroEhcacheManager" />  
  25.     </bean>  
  26.   
  27.     <!-- Shiro 過濾器 -->  
  28.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  29.         <!-- Shiro的核心安全接口,這個屬性是必須的 -->  
  30.         <property name="securityManager" ref="securityManager" />  
  31.         <!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->  
  32.         <property name="loginUrl" value="/login" />  
  33.         <property name="successUrl" value="/certification" />  
  34.         <property name="unauthorizedUrl" value="/error" />  
  35.         <!-- Shiro連接約束配置,即過濾鏈的定義 -->  
  36.         <property name="filterChainDefinitions">  
  37.             <value>  
  38.                 /login = authc  
  39.                 /exit = anon  
  40.                 /admin/security/list=authcBasic,perms[admin:read]  
  41.                 /admin/security/save=authcBasic,perms[admin:insert]  
  42.                 /admin/security/update=authcBasic,perms[admin:update]  
  43.                 /admin/security/delete=authcBasic,perms[admin:delete]  
  44.             </value>  
  45.         </property>  
  46.     </bean>  
  47.   
  48.     <!-- 用戶授權信息Cache, 採用EhCache -->  
  49.     <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
  50.         <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />  
  51.     </bean>  
  52.   
  53.     <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->  
  54.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  55.   
  56.     <!-- AOP式方法級權限檢查 -->  
  57.     <bean  
  58.         class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
  59.         depends-on="lifecycleBeanPostProcessor">  
  60.         <property name="proxyTargetClass" value="true" />  
  61.     </bean>  
  62.     <bean  
  63.         class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  64.         <property name="securityManager" ref="securityManager" />  
  65.     </bean>  

 第五步、shiro退出登錄的實現

Java代碼  收藏代碼
  1.        第一種方式  
  2.        /** 
  3.  * 退出登陸操作 
  4.  */  
  5. @RequestMapping(value = "/exit", method = RequestMethod.GET)  
  6. public String exit(RedirectAttributes redirectAttributes, HttpSession session) {  
  7.     session.removeAttribute(Constants.Token.RONCOO);  
  8.     SecurityUtils.getSubject().logout();  
  9.     redirectAttributes.addFlashAttribute("msg""您已經安全退出");  
  10.     return redirect("/login");  
  11. }  
  12.   
  13. 第二種方式:在shiroFilter的約束配置中配置  
  14. <!-- Shiro連接約束配置,即過濾鏈的定義 -->  
  15. <property name="filterChainDefinitions">  
  16.     <value>  
  17.         /exit = logout  
  18.     </value>  
  19. </property>     


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章