shiro與項目整合(spring環境)

1、shiro的jar包
shiro-web的jar、shiro-spring的jar、shiro-core的jar
2、在web.xml中配置shiro的filter
在web系統中,shiro也通過filter進行攔截。filter攔截後加你個操作權交給spring中配置的filterChain(過濾鏈),shiro也提供很多filter。
在web.xml中配置filter

<!-- shiro的filter -->
	<!-- shiro過慮器,DelegatingFilterProxy通過代理模式將spring容器中的bean和filter關聯起來 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<!-- 設置true由servlet容器控制filter的生命週期 -->
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
		<!-- 設置spring容器filter的bean id,如果不設置則找與filter-name一致的bean-->
		<init-param>
			<param-name>targetBeanName</param-name>
			<param-value>shiroFilter</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

3、applicationContext-shiro.xml
在applicationContext-shiro.xml中配置web.xml中filter對應spring容器中的bean。

<!-- web.xml中shiro的filter對應的bean -->
<!-- Shiro 的Web過濾器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 -->
		<property name="loginUrl" value="/login.action" />
		<!-- 認證成功統一跳轉到first.action,建議不配置,shiro認證成功自動到上一個請求路徑 -->
		<property name="successUrl" value="/first.action"/>
		<!-- 通過unauthorizedUrl指定沒有權限操作時跳轉頁面-->
		<property name="unauthorizedUrl" value="/refuse.jsp" />		
		<!-- 過慮器鏈定義,從上向下順序執行,一般將/**放在最下邊 -->
		<property name="filterChainDefinitions">
			<value>
				<!-- 對靜態資源設置匿名訪問 -->
				/images/** = anon
				/js/** = anon
				/styles/** = anon
				<!-- 驗證碼,可匿名訪問 -->
				/validatecode.jsp = anon
				
				<!-- 請求 logout.action地址,shiro去清除session-->
				/logout.action = logout
				<!--商品查詢需要商品查詢權限 ,取消url攔截配置,使用註解授權方式 -->
				<!-- /items/queryItems.action = perms[item:query]
				/items/editItems.action = perms[item:edit] -->
				<!-- 配置記住我或認證通過可以訪問的地址 -->
				/index.jsp  = user
				/first.action = user
				/welcome.jsp = user
				<!-- /** = authc 所有url都必須認證通過纔可以訪問-->
				/** = authc
				<!-- /** = anon所有url都可以匿名訪問 -->
			</value>
		</property>
	</bean>

<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="customRealm" />
	</bean>

<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
</bean>

4、靜態資源

<!-- 對靜態資源設置匿名訪問 -->
				/images/** = anon
				/js/** = anon
				/styles/** = anon

5、登陸
5.1原理
使用FormAuthenticationFilter過濾器實現,原理如下:
當用戶沒有認證時,請求loginURL進行認證,用戶身份和用戶密碼提交數據到loginURL,FormAuthenticationFilter攔截住取出request中的username和password(兩個參數名是可以配置的),FormAuthenticationFilter調用realm傳入一個token(username和password),realm認證時根據username查詢用戶信息(在ActiveUser中存儲,包括userID,userCode,username,menus).如果查詢不到,realm返回null,FormAuthenticationFilter向request域中填充一個參數(記錄了異常信息)
5.2登錄頁面
由於FormAuthenticationFilter的用戶身份和密碼的input的默認值(username和password),修改頁面的賬號和密碼的input的名稱爲username和password。
5.3登錄代碼實現

//登陸提交地址,和applicationContext-shiro.xml中配置的loginurl一致
	@RequestMapping("login")
	public String login(HttpServletRequest request)throws Exception{
		
		//如果登陸失敗從request中獲取認證異常信息,shiroLoginFailure就是shiro異常類的全限定名
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		//根據shiro返回的異常類路徑判斷,拋出指定異常信息
		if(exceptionClassName!=null){
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				//最終會拋給異常處理器
				throw new CustomException("賬號不存在");
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				throw new CustomException("用戶名/密碼錯誤");
			} else if("randomCodeError".equals(exceptionClassName)){
				throw new CustomException("驗證碼錯誤 ");
			}else {
				throw new Exception();//最終在異常處理器生成未知錯誤
			}
		}
		//此方法不處理登陸成功(認證成功),shiro認證成功會自動跳轉到上一個請求路徑
		//登陸失敗還到login頁面
		return "login";
	}

6、退出
使用logoutfilter
不用我們去實現退出,只要去訪問一個退出的url(該url可以不存在),由logoutfilter攔截住,清楚session。
在applicationContext-shiro.xml配置logoutfilter:

<!-- 請求 logout.action地址,shiro去清除session-->
				/logout.action = logout

7、認證信息在頁面展示
1、認證後用戶菜單在首頁顯示
2、認證後用戶的信息在頁頭展示

realm從數據庫查詢用戶信息,將用戶菜單、username、usercode等設置在SimpleAuthenticationInfo中。

@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		// token是用戶輸入的用戶名和密碼 
		// 第一步從token中取出用戶名
		String userCode = (String) token.getPrincipal();

		// 第二步:根據用戶輸入的userCode從數據庫查詢
		SysUser sysUser = null;
		try {
			sysUser = sysService.findSysUserByUserCode(userCode);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// 如果查詢不到返回null
		if(sysUser==null){//
			return null;
		}
		// 從數據庫查詢到密碼
		String password = sysUser.getPassword();
		
		//鹽
		String salt = sysUser.getSalt();

		// 如果查詢到返回認證信息AuthenticationInfo
		
		//activeUser就是用戶身份信息
		ActiveUser activeUser = new ActiveUser();
		
		activeUser.setUserid(sysUser.getId());
		activeUser.setUsercode(sysUser.getUsercode());
		activeUser.setUsername(sysUser.getUsername());
		//..
		
		//根據用戶id取出菜單
		List<SysPermission> menus  = null;
		try {
			//通過service取出菜單 
			menus = sysService.findMenuListByUserId(sysUser.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//將用戶菜單 設置到activeUser
		activeUser.setMenus(menus);

		//將activeUser設置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password,ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
	}

修改first.action將認證信息在頁面展示

//系統首頁
	@RequestMapping("/first")
	public String first(Model model)throws Exception{
		
		//從shiro的session中取activeUser
		Subject subject = SecurityUtils.getSubject();
		//取身份信息
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		//通過model傳到頁面
		model.addAttribute("activeUser", activeUser);
		
		return "/first";
	}

8、授權過濾器測試
8.1 使用PermissionsAuthorizationFilter
在applicationContext-shiro.xml中配置url所對應的權限。

測試流程:
1、在applicationContext-shiro.xml中配置filter規則。

<!--商品查詢需要商品查詢權限  -->
	/items/queryItems.action = perms[item:query]

2、用戶在認證通過後,請求 /items/queryItems.action
3、被PermissionsAuthorizationFilter攔截,發現需要“item:query”權限。
4、PermissionsAuthorizationFilter調用realm中的doGetAuthorizationInfo獲取數據庫正確的權限
5、PermissionsAuthorizationFilter對item:query和從realm中獲取權限進行對比,如果“item:query”在realm返回的權限列表中,授權通過。
8.2 創建refuse.jsp,配置拒絕

<!-- 通過unauthorizedUrl指定沒有權限操作時跳轉頁面-->
		<property name="unauthorizedUrl" value="/refuse.jsp" />		

問題總結:
1.在applicationContext-shiro.xml中配置過濾器連接,需要將全部的url和權限對應起來進行配置,比較麻煩。
2、每次授權都需要調用realm查詢數據庫,對於系統性能有很大的影響,可以通過shiro緩存來解決。

9、shiro的過濾器

過濾器簡稱	對應的java類
anon	org.apache.shiro.web.filter.authc.AnonymousFilter
authc	org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic	org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
perms	org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port	org.apache.shiro.web.filter.authz.PortFilter
rest	org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles	org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
ssl	org.apache.shiro.web.filter.authz.SslFilter
user	org.apache.shiro.web.filter.authc.UserFilter
logout	org.apache.shiro.web.filter.authc.LogoutFilter

anon:例子/admins/=anon 沒有參數,表示可以匿名使用。
authc:例如/admins/user/
=authc表示需要認證(登錄)才能使用,FormAuthenticationFilter是表單認證,沒有參數
perms:例子/admins/user/=perms[user:add:*],參數可以寫多個,多個時必須加上引號,並且參數之間用逗號分割,例如/admins/user/=perms[“user:add:,user:modify:”],當有多個參數時必須每個參數都通過才通過,想當於isPermitedAll()方法。
user:例如/admins/user/**=user沒有參數表示必須存在用戶, 身份認證通過或通過記住我認證通過的可以訪問,當登入操作時不做檢查

10、加鹽的認證
10.1需求
修改realm的doGetAuthenticationInfo,從數據庫查詢用戶信息,realm返回的用戶信息包括(MD5加密後的串和salt),實現shiro進行散列串的校驗。
10.2修改doGetAuthenticationInfo從數據庫查詢用戶信息

//realm的認證方法,從數據庫查詢用戶信息
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		// token是用戶輸入的用戶名和密碼 
		// 第一步從token中取出用戶名
		String userCode = (String) token.getPrincipal();

		// 第二步:根據用戶輸入的userCode從數據庫查詢
		SysUser sysUser = null;
		try {
			sysUser = sysService.findSysUserByUserCode(userCode);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// 如果查詢不到返回null
		if(sysUser==null){//
			return null;
		}
		// 從數據庫查詢到密碼
		String password = sysUser.getPassword();
		
		//鹽
		String salt = sysUser.getSalt();

		// 如果查詢到返回認證信息AuthenticationInfo
		
		//activeUser就是用戶身份信息
		ActiveUser activeUser = new ActiveUser();
		
		activeUser.setUserid(sysUser.getId());
		activeUser.setUsercode(sysUser.getUsercode());
		activeUser.setUsername(sysUser.getUsername());
		//..
		
		//根據用戶id取出菜單
		List<SysPermission> menus  = null;
		try {
			//通過service取出菜單 
			menus = sysService.findMenuListByUserId(sysUser.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//將用戶菜單 設置到activeUser
		activeUser.setMenus(menus);
		
		
		//將activeUser設置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password,ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
	}

10.3設置憑證匹配器
數據庫中存儲到的MD5的散列值,在realm中需要設置數據庫中的散列值它使用散列算法及散列次數,讓shiro進行散列對比時和原始數據庫中的散列值使用的算法一致。

<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
	<!-- 將憑證匹配器設置到realm中,realm按照憑證匹配器的要求進行散列 -->
	<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>

<!-- 憑證匹配器 -->
<bean id="credentialsMatcher"
	class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
	<property name="hashAlgorithmName" value="md5" />
	<property name="hashIterations" value="1" />
</bean>

11、授權
11.1需求
修改realm的doGetAuthorizationInfo,從數據庫查詢權限信息。
使用註解式授權方法。
使用jsp標籤授權方法。
11.2修改doGetAuthorizationInfo從數據庫查詢權限

// 用於授權
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		//從 principals獲取主身份信息
		//將getPrimaryPrincipal方法返回值轉爲真實身份類型(在上邊的doGetAuthenticationInfo認證通過填充到SimpleAuthenticationInfo中身份類型),
		ActiveUser activeUser =  (ActiveUser) principals.getPrimaryPrincipal();
		
		//根據身份信息獲取權限信息
		//從數據庫獲取到權限數據
		List<SysPermission> permissionList = null;
		try {
			permissionList = sysService.findPermissionListByUserId(activeUser.getUserid());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//單獨定一個集合對象 
		List<String> permissions = new ArrayList<String>();
		if(permissionList!=null){
			for(SysPermission sysPermission:permissionList){
				//將數據庫中的權限標籤 符放入集合
				permissions.add(sysPermission.getPercode());
			}
		}
		
		
		//查到權限數據,返回授權信息(要包括 上邊的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//將上邊查詢到授權信息填充到simpleAuthorizationInfo對象中
		simpleAuthorizationInfo.addStringPermissions(permissions);

		return simpleAuthorizationInfo;
	}

11.3開啓controller類aop支持
對系統中類的方法給用戶授權,建議在controller層進行方法授權。

在springmvc.xml中配置:

<!-- 使用spring組件掃描 -->
	<context:component-scan base-package="cn.itcast.ssm.controller" />
	
	<!-- 開啓aop,對類代理 -->
	<aop:config proxy-target-class="true"></aop:config>
	<!-- 開啓shiro註解支持 -->
	<bean
		class="
org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>

11.4在controller方法中添加註解

@RequestMapping(value="/editItems",method={RequestMethod.GET})
	@RequiresPermissions("item:update")//執行此方法需要"item:update"權限
	public String editItems(Model model,Integer id)throws Exception{
		
		//將id傳到頁面
		model.addAttribute("id", id);
		
		//調用 service查詢商品信息
		ItemsCustom itemsCustom = itemsService.findItemsById(id);
				
		model.addAttribute("itemsCustom", itemsCustom);

		//return "editItem_2";
		return "editItem";
		
	}

11.5 jsp標籤授權
jsp頁面添加:

<%@ tagliburi="http://shiro.apache.org/tags" prefix="shiro" %>

標籤名稱 標籤條件(均是顯示標籤內容)
shiro:authenticated 登錄之後
shiro:notAuthenticated 不在登錄狀態時
shiro:guest 用戶在沒有RememberMe時
shiro:user 用戶在RememberMe時
<shiro:hasAnyRoles name=“abc,123” > 在有abc或者123角色時
<shiro:hasRole name=“abc”> 擁有角色abc
<shiro:lacksRole name=“abc”> 沒有角色abc
<shiro:hasPermission name=“abc”> 擁有權限資源abc
<shiro:lacksPermission name=“abc”> 沒有abc權限資源
shiro:principal 顯示用戶身份名稱
<shiro:principal property=“username”/> 顯示用戶身份中的屬性值

修改itemsList.jsp頁面:

<td>
	<!-- 有item:update權限才顯示修改鏈接,沒有該 權限不顯示,相當 於if(hasPermission(item:update)) -->
	<shiro:hasPermission name="item:update">
	<a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id}">修改</a>
	</shiro:hasPermission>
	</td>

11.6授權測試
當調用controller的一個方法,由於該方法加了@RequiresPermissions(“item:query”) ,shiro調用realm獲取數據庫中的權限信息,看"item:query"是否在權限數據中存在,如果不存在就拒絕訪問,如果存在就授權通過。

當展示一個jsp頁面時,頁面中如果遇到<shiro:hasPermission name=“item:update”>,shiro調用realm獲取數據庫中的權限信息,看"item:update"是否在權限數據中存在,如果不存在就拒絕訪問,如果存在就授權通過。
問題:只要遇到註解或jsp標籤的授權,都會調用realm方法查詢數據庫,需使用緩存解決此問題

12、shiro緩存
針對上邊授權頻繁查詢數據庫,需要使用shiro緩存。
12.1緩存流程
shiro中提供了對認證信息和授權信息的緩存。shiro默認是關閉認證信息緩存的,對於授權信息的緩存shiro默認開啓的。主要研究授權信息緩存,因爲授權的數據量大。

用戶認證通過:
該用戶第一次授權,調用realm查詢數據庫
該用戶第二次授權,不調用realm查詢數據庫,直接從緩存中取出授權信息(權限標識符)
12.2使用ehcache
(1)添加ehcache的jar包
ehcache-core的jar,shiro-ehcache的jar
(2)配置cacheManager

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="customRealm" />
		<!-- 注入緩存管理器 -->
		<property name="cacheManager" ref="cacheManager"/>
		</bean>
<!-- 緩存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    	<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
    </bean>

(3)shiro-encache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
	<!--diskStore:緩存數據持久化的目錄 地址  -->
	<diskStore path="F:\develop\ehcache" />
	<defaultCache 
		maxElementsInMemory="1000" 
		maxElementsOnDisk="10000000"
		eternal="false" 
		overflowToDisk="false" 
		diskPersistent="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120" 
		diskExpiryThreadIntervalSeconds="120"
		memoryStoreEvictionPolicy="LRU">
	</defaultCache>
</ehcache>

(4)緩存清空
如果用戶正常退出,緩存自動清空
如果用戶非正常退出,緩存自動清空

如果修改了用戶的權限,而用戶不退出系統,修改的權限無法立即生效,需要手動進行編程實現:
在權限修改後調用realm的clearCache方法清除緩存。下邊的代碼正常開發時要放在service中調用。
在service中,權限修改後調用realm的方法
在realm中定義clearCached方法:

//清除緩存
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

13、sessionManager
和shiro整合後,使用shiro的session管理,shiro提供sessionDao操作會話數據。

配置sessionManager

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="customRealm" />
		<!-- 注入緩存管理器 -->
		<property name="cacheManager" ref="cacheManager"/>
		<!-- 注入session管理器 -->
		<property name="sessionManager" ref="sessionManager" />
		<!-- 記住我 -->
		<property name="rememberMeManager" ref="rememberMeManager"/>
		
	</bean>
<!-- 會話管理器 -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- session的失效時長,單位毫秒 -->
        <property name="globalSessionTimeout" value="600000"/>
        <!-- 刪除失效的session -->
        <property name="deleteInvalidSessions" value="true"/>
    </bean>

14、驗證碼
思路:
shiro使用FormAuthenticationFilter進行表單認證,驗證校驗的功能應該加在FormAuthenticationFilter中,在認證之前進行驗證碼校驗。
需要寫FormAuthenticationFilter的子類,繼承FormAuthenticationFilter,改寫它的認證方法,在認證之前進行驗證碼校驗。

自定義FormAuthenticationFilter:

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

	//原FormAuthenticationFilter的認證方法
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		//在這裏進行驗證碼的校驗
		
		//從session獲取正確驗證碼
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session =httpServletRequest.getSession();
		//取出session的驗證碼(正確的驗證碼)
		String validateCode = (String) session.getAttribute("validateCode");
		
		//取出頁面的驗證碼
		//輸入的驗證和session中的驗證進行對比 
		String randomcode = httpServletRequest.getParameter("randomcode");
		if(randomcode!=null && validateCode!=null && !randomcode.equals(validateCode)){
			//如果校驗失敗,將驗證碼錯誤失敗信息,通過shiroLoginFailure設置到request中
			httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
			//拒絕訪問,不再校驗賬號和密碼 
			return true; 
		}
		return super.onAccessDenied(request, response);
	}
}

配置自定義的FormAuthenticationFilter

<!-- Shiro 的Web過濾器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 -->
		<property name="loginUrl" value="/login.action" />
		<!-- 認證成功統一跳轉到first.action,建議不配置,shiro認證成功自動到上一個請求路徑 -->
		<property name="successUrl" value="/first.action"/>
		<!-- 通過unauthorizedUrl指定沒有權限操作時跳轉頁面-->
		<property name="unauthorizedUrl" value="/refuse.jsp" />
		<!-- 自定義filter配置 -->
		<property name="filters">
			<map>
				<!-- 將自定義 的FormAuthenticationFilter注入shiroFilter中-->
				<entry key="authc" value-ref="formAuthenticationFilter" />
			</map>
		</property>
<!-- 自定義form認證過慮器 -->
<!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用`在這裏插入代碼片`戶賬號、密碼及loginurl將採用默認值,建議配置 -->
	<bean id="formAuthenticationFilter" 
	class="cn.itcast.ssm.shiro.CustomFormAuthenticationFilter ">
		<!-- 表單中賬號的input名稱 -->
		<property name="usernameParam" value="username" />
		<!-- 表單中密碼的input名稱 -->
		<property name="passwordParam" value="password" />
		<!-- 記住我input的名稱 -->
		<property name="rememberMeParam" value="rememberMe"/>
 </bean>

在filter配置匿名訪問驗證碼jsp

<!-- 配置記住我或認證通過可以訪問的地址 -->
				/index.jsp  = user
				/first.action = user
				/welcome.jsp = user

15、記住我
用戶登錄選擇“自動登錄”本次登錄成功會向cookie寫身份信息,下次登錄從cookie中取出身份信息實現自動登錄

1、用戶身份實現java.io.Serializable接口

向cookie記錄身份信息需要用戶身份信息對象實現序列化接口,如下:

public class ActiveUser implements java.io.Serializable

2、配置rememberMeManager

<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="customRealm" />
		<!-- 注入緩存管理器 -->
		<property name="cacheManager" ref="cacheManager"/>
		<!-- 注入session管理器 -->
		<property name="sessionManager" ref="sessionManager" />
		<!-- 記住我 -->
		<property name="rememberMeManager" ref="rememberMeManager"/>
		
	</bean>
<!-- rememberMeManager管理器,寫cookie,取出cookie生成用戶信息 -->
	<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
		<property name="cookie" ref="rememberMeCookie" />
	</bean>
	<!-- 記住我cookie -->
	<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
		<!-- rememberMe是cookie的名字 -->
		<constructor-arg value="rememberMe" />
		<!-- 記住我cookie生效時間30天 -->
		<property name="maxAge" value="2592000" />
	</bean>

3、登錄頁面

<td><input type="checkbox" name="rememberMe"/>自動登錄</td>

4、配置rememberMe的input名稱

<!-- 自定義form認證過慮器 -->
<!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用戶賬號、密碼及loginurl將採用默認值,建議配置 -->
	<bean id="formAuthenticationFilter" 
	class="cn.itcast.ssm.shiro.CustomFormAuthenticationFilter ">
		<!-- 表單中賬號的input名稱 -->
		<property name="usernameParam" value="username" />
		<!-- 表單中密碼的input名稱 -->
		<property name="passwordParam" value="password" />
		<!-- 記住我input的名稱 -->
		<property name="rememberMeParam" value="rememberMe"/>
 </bean>

5、測試
自動登錄後,需要查看cookie是否有rememberMe
6、使用UserFilter
如果設置記住我,下次訪問某些url時可以不用登錄,將記住我即可訪問的地址配置讓UserFilter攔截

<!-- 配置記住我或認證通過可以訪問的地址 -->
				/index.jsp  = user
				/first.action = user
				/welcome.jsp = user
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章