Shiro学习笔记——(8)实战之缓存,验证码,记住我

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shaohe18362202126/article/details/79832985

一、缓存

(1)缓存流程

shiro中提供了对认证信息和授权信息的缓存。shiro默认是关闭认证信息缓存的,对于授权信息的缓存shiro默认开启的。主要研究授权信息缓存,因为授权的数据量大。 

用户认证通过。

该用户第一次授权:调用realm查询数据库

该用户第二次授权:不调用realm查询数据库,直接从缓存中取出授权信息(权限标识符)。

使用ehcache缓存框架

(2)配置cacheManager



(3)创建shiro-ehcache.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中

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

测试清除缓存controller方法:

(5)sessionManager

和shiro整合后,使用shiro的session管理,shiro提供sessionDao操作会话数据。

配置sessionManager



二、验证码

(1)流程

shiro使用FormAuthenticationFilter进行表单认证,验证校验的功能应该加在FormAuthenticationFilter中,在认证之前进行验证码校验。

需要写FormAuthenticationFilter的子类,继承FormAuthenticationFilter,改写它的认证方法,在认证之前进行验证码校验。

(2)自定义FormAuthenticationFilter


(3)配置自定义FormAuthenticationFilter


注入formAuthenticationFilter

(4)在login.action对验证错误 进行解析


三、记住我

用户登陆选择“自动登陆”本次登陆成功会向cookie写身份信息,下次登陆从cookie中取出身份信息实现自动登陆。

(1)用户身份实现java.io.Serializable接口

向cookie记录身份信息需要用户身份信息对象实现序列化接口



(2)配置rememeberMeManager


(3)登陆页面


(4)配置rememberMe的input名称


(5)使用UserFilter

如果设置记住我,下次访问某些url时可以不用登陆。将记住我即可访问的地址配置让UserFilter拦截。



猜你喜欢

转载自blog.csdn.net/shaohe18362202126/article/details/79832985