引言:Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架
Cache 作用
因为shiro每次读取权限(刷新或其他操作)
的时候都要从数据库中访问权限信息
,但是一般实际应用中规定好的用户权限和资源是不变的,所以只需要读取一次即可,所以我们可以使用Cache缓存
来减轻DB访问压力,从而提高系统的查询效率(一般放入缓存的是查询为主,增删改压力会很大)
- Cache 缓存: 计算机内存中一段数据
- 作用: 用来减轻DB的访问压力,从而提高系统的查询效率
- 流程:
使用shiro中默认EhCache实现本地缓存
引入依赖
<!--引入shiro和ehcache-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.3</version>
</dependency>
开启缓存ShiroConfig
@Configuration
public class ShiroConfig {
/*
* 1.创建shirofilter,使用工厂构建,
* 定义一个shirofilter获取方法,负债拦截所有请求
* DefaultWebSecurityManager defaultWebSecurityManager
* 传入,因为shirofilter依赖于DefaultWebSecurityManager进行构建
* */
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//注入安全管理器DefaultWebSecurityManager
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统公共资源
Map<String,String> map = new HashMap<String,String>();
map.put("/user/login","anon");//anon 设置为公共资源 放行资源放在下面
map.put("/user/register","anon");//anon 设置为公共资源 放行资源放在下面
map.put("/register.jsp","anon");//anon 设置为公共资源 放行资源放在下面
map.put("/user/getImage","anon");
map.put("/**","authc");//authc 请求这个资源需要认证和授权
//默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//返回一个shiroFilterFactoryBean
return shiroFilterFactoryBean;
}
/*
* 2.创建SecurityManager,这里是DefaultWebSecurityManager
*
* */
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置Realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
/*
* 3.创建realm自定义的数据域
* */
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
//1.修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法
credentialsMatcher.setHashAlgorithmName("md5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
//2.开启缓存管理
//开启全局缓存管理
customerRealm.setCachingEnabled(true);
//开启认证缓存
customerRealm.setAuthenticationCachingEnabled(true);
//设置认证缓存名字方便查找
customerRealm.setAuthorizationCacheName("authorizationCache");
//开启授权缓存
customerRealm.setAuthorizationCachingEnabled(true);
//设置授权缓存名字方便查找
customerRealm.setAuthorizationCacheName("authorizationCache");
//对自定义realm开启缓存,创建EhCacheManager
customerRealm.setCacheManager(new EhCacheManager());
return customerRealm;
}
}
启动测试
只有第一次登陆的时候调用了权限查询,然后登陆后不断刷新发现并没有调用到授权验证,说明缓存实现
—end