如下應用由springmvc結合shiro 認證與受權配置java
1\spring-shiro.xmlweb
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 10 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd 11 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 12 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 13 <property name="securityManager" ref="securityManager"></property> 14 <!-- 身份認證失敗,則跳轉到登陸頁面的配置 --> 15 <property name="loginUrl" value="/login.do"></property> 16 <!-- 權限認證失敗,則跳轉到指定頁面 --> 17 <property name="unauthorizedUrl" value="/refuse.jsp"></property> 18 <!-- 權限認證成功,則跳轉到指定頁面 --> 19 <property name="successUrl" value="/main.do" /> 20 <!-- 自定義filter配置 --> 21 <property name="filters"> 22 <map> 23 <!-- 將自定義 的FormAuthenticationFilter注入shiroFilter中--> 24 <entry key="authc" value-ref="formAuthenticationFilter" /> 25 </map> 26 </property> 27 <property name="filterChainDefinitions"> 28 <value> 29 /login.do = authc 30 /main.do = authc 31 /logout.do = logout 32 /refuse.jsp = anon 33 34 /** = anon 35 </value> 36 </property> 37 </bean> 38 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 39 <property name="realm" ref="customRealm"></property> 40 <!-- 注入緩存管理器 --> 41 <property name="cacheManager" ref="cacheManager"/> 42 <!-- 注入session管理器 --> 43 <property name="sessionManager" ref="sessionManager" /> 44 <!-- 記住我 --> 45 <property name="rememberMeManager" ref="rememberMeManager"/> 46 </bean> 47 48 <!-- realm --> 49 <bean id="customRealm" class="com.telecom.shiro.CustomRealm"> 50 <!-- 將憑證匹配器設置到realm中,realm按照憑證匹配器的要求進行散列 --> 51 <property name="credentialsMatcher" ref="credentialsMatcher"/> 52 </bean> 53 <!-- 憑證匹配器 --> 54 <bean id="credentialsMatcher" 55 class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> 56 <property name="hashAlgorithmName" value="md5" /> 57 <property name="hashIterations" value="1" /> 58 </bean> 59 60 <!-- 緩存管理器 --> 61 <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 62 <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/> 63 </bean> 64 65 <!-- 會話管理器 --> 66 <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 67 <!-- session的失效時長,單位毫秒 --> 68 <property name="globalSessionTimeout" value="600000"/> 69 <!-- 刪除失效的session --> 70 <property name="deleteInvalidSessions" value="true"/> 71 72 </bean> 73 74 <!-- 自定義form認證過慮器 --> 75 <!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用戶帳號、密碼及loginurl將採用默認值,建議配置 --> 76 <bean id="formAuthenticationFilter" 77 class="com.telecom.shiro.CustomFormAuthenticationFilter "> 78 <!-- 表單中帳號的input名稱 --> 79 <property name="usernameParam" value="username" /> 80 <!-- 表單中密碼的input名稱 --> 81 <property name="passwordParam" value="password" /> 82 <!-- 記住我input的名稱 --> 83 <property name="rememberMeParam" value="rememberMe"/> 84 </bean> 85 86 <!-- rememberMeManager管理器,寫cookie,取出cookie生成用戶信息 --> 87 <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager"> 88 <property name="cookie" ref="rememberMeCookie" /> 89 </bean> 90 <!-- 記住我cookie --> 91 <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> 92 <!-- rememberMe是cookie的名字 --> 93 <constructor-arg value="rememberMe" /> 94 <!-- 記住我cookie生效時間30天 --> 95 <property name="maxAge" value="2592000" /> 96 </bean> 97 98 </beans>
2\shiro-ehcache.xmlspring
1 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> 3 <!--diskStore:緩存數據持久化的目錄 地址 --> 4 <diskStore path="/home/ljj/JAVA/cache" /> 5 <defaultCache 6 maxElementsInMemory="1000" 7 maxElementsOnDisk="10000000" 8 eternal="false" 9 overflowToDisk="false" 10 diskPersistent="false" 11 timeToIdleSeconds="120" 12 timeToLiveSeconds="120" 13 diskExpiryThreadIntervalSeconds="120" 14 memoryStoreEvictionPolicy="LRU"> 15 </defaultCache> 16 </ehcache>
3\web.xmlapache
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 <display-name>telecom</display-name> 4 <context-param> 5 <param-name>contextConfigLocation</param-name> 6 <param-value>classpath:applicationContext.xml,classpath:spring-mybatis.xml,classpath:spring-shiro.xml</param-value> 7 </context-param> 8 <listener> 9 <description>spring監聽器</description> 10 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 11 </listener> 12 13 14 <servlet> 15 <description>spring mvc servlet</description> 16 <servlet-name>springMvc</servlet-name> 17 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 18 <init-param> 19 <description>spring mvc 配置文件</description> 20 <param-name>contextConfigLocation</param-name> 21 <param-value>classpath:spring-mvc.xml</param-value> 22 </init-param> 23 <init-param> 24 <param-name>activeReverseAjaxEnabled</param-name> 25 <param-value>true</param-value> 26 </init-param> 27 <load-on-startup>1</load-on-startup> 28 </servlet> 29 <servlet-mapping> 30 <servlet-name>springMvc</servlet-name> 31 <url-pattern>*.do</url-pattern> 32 </servlet-mapping> 33 34 35 <!--配置 shiro filter --> 36 <!-- shiro過濾器 ,DelegatingFilterProxy經過代理模式將spring容器的bean和filter關聯 --> 37 <filter> 38 <filter-name>shiroFilter</filter-name> 39 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 40 <init-param> 41 <param-name>targetFilterLifecycle</param-name> 42 <param-value>true</param-value> 43 </init-param> 44 <init-param> 45 <param-name>targetBeanName</param-name> 46 <param-value>shiroFilter</param-value> 47 </init-param> 48 </filter> 49 <filter-mapping> 50 <filter-name>shiroFilter</filter-name> 51 <url-pattern>/*</url-pattern> 52 </filter-mapping> 53 54 <filter> 55 <filter-name>characterEncodingFilter</filter-name> 56 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 57 <init-param> 58 <param-name>encoding</param-name> 59 <param-value>UTF-8</param-value> 60 </init-param> 61 <init-param> 62 <param-name>forceEncoding</param-name> 63 <param-value>true</param-value> 64 </init-param> 65 </filter> 66 67 <filter-mapping> 68 <filter-name>characterEncodingFilter</filter-name> 69 <url-pattern>/*</url-pattern> 70 </filter-mapping> 71 72 <listener> 73 <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 74 </listener> 75 <welcome-file-list> 76 <welcome-file>index.jsp</welcome-file> 77 </welcome-file-list> 78 </web-app>
4\CustomRealm.java(自定義域)spring-mvc
1 package com.telecom.shiro; 2 3 import javax.servlet.ServletRequest; 4 import javax.servlet.ServletResponse; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpSession; 7 8 import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; 9 10 public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { 11 @Override 12 protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { 13 // TODO Auto-generated method stub 14 HttpServletRequest httpServletRequest = (HttpServletRequest)request; 15 HttpSession httpSession = httpServletRequest.getSession(); 16 //session中驗證碼 17 String validateCode = (String) httpSession.getAttribute("validateCode"); 18 19 //界面中驗證碼 20 String randomcode = httpServletRequest.getParameter("randomcode"); 21 22 System.out.println("驗證:::::"+validateCode+"輸入的驗證:::::"+randomcode); 23 if(validateCode != null && randomcode != null && !validateCode.equals(randomcode)){ 24 //若是校驗失敗,將驗證碼錯誤失敗信息,經過shiroLoginFailure設置到request中 25 httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError"); 26 27 //拒絕訪問,再也不校驗帳號和密碼 28 return true; 29 } 30 return super.onAccessDenied(request, response); 31 } 32 }
5\自定義表單CustomFormAuthenticationFilter.java緩存
1 package com.telecom.shiro; 2 3 import javax.servlet.ServletRequest; 4 import javax.servlet.ServletResponse; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpSession; 7 8 import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; 9 10 public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { 11 @Override 12 protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { 13 // TODO Auto-generated method stub 14 HttpServletRequest httpServletRequest = (HttpServletRequest)request; 15 HttpSession httpSession = httpServletRequest.getSession(); 16 //session中驗證碼 17 String validateCode = (String) httpSession.getAttribute("validateCode"); 18 19 //界面中驗證碼 20 String randomcode = httpServletRequest.getParameter("randomcode"); 21 22 System.out.println("驗證:::::"+validateCode+"輸入的驗證:::::"+randomcode); 23 if(validateCode != null && randomcode != null && !validateCode.equals(randomcode)){ 24 //若是校驗失敗,將驗證碼錯誤失敗信息,經過shiroLoginFailure設置到request中 25 httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError"); 26 27 //拒絕訪問,再也不校驗帳號和密碼 28 return true; 29 } 30 return super.onAccessDenied(request, response); 31 } 32 }
6\Controllercookie
@RequestMapping("login") public String login(){ System.out.println("進行登陸"); String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); if(exceptionClassName != null){ if(UnknownAccountException.class.getName().equals(exceptionClassName)){ System.out.println("帳號不存在!"); request.setAttribute("message", "帳號不存在!"); }else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){ request.setAttribute("message", "密碼錯誤!"); System.out.println("帳號/密碼錯誤!"); }else if("randomCodeError".equals(exceptionClassName)){ request.setAttribute("message", "驗證碼錯誤!"); System.out.println("驗證碼錯誤!"); }else { request.setAttribute("message", "未知錯誤!"); System.out.println("未知錯誤!"); } } return "/main/login"; }