springboot shiro ehcache redis 简单使用
引入相关pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency> <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.1</version>
</dependency> <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.1</version>
</dependency>
配置properties
shiro.loginUrl=/login
shiro.unauthorizedUrl=/403 spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.timeout=2000
编写ShiroConfig 配置类
@Bean
public Realm realm(){
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return userRealm;
} @Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
/**
* 处理@RequiresRole等shiro注解失效问题
*/
//autoProxyCreator.setUsePrefix(true);
autoProxyCreator.setProxyTargetClass(true);
return autoProxyCreator;
} @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
return authorizationAttributeSourceAdvisor;
} @Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition(){
DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition();
Map<String,String> pathDefinitions = new LinkedHashMap<>();
pathDefinitions.put("/loginDo","anon");
pathDefinitions.put("/**","user");
//authc user anon
chain.addPathDefinitions(pathDefinitions);
return chain;
} /**
* 密码验证
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
RetryLimitHashedCredentialsMatcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("MD5");
credentialsMatcher.setHashIterations(3);
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
} @Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
} @Bean
public RedisCacheSessionDAO redisCacheSessionDAO(){
RedisCacheSessionDAO redisCacheSessionDAO = new RedisCacheSessionDAO();
return redisCacheSessionDAO;
} @Bean
public SessionManager sessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setGlobalSessionTimeout(1000 * 60 * 30);
sessionManager.setSessionIdCookieEnabled(true);
sessionManager.setSessionIdCookie(sessionIdCookie());
//sessionManager.setSessionDAO(new EnterpriseCacheSessionDAO());
sessionManager.setSessionDAO(redisCacheSessionDAO());
sessionManager.setDeleteInvalidSessions(true);//删除过期session
sessionManager.setSessionValidationSchedulerEnabled(true);//定期检查session
return sessionManager;
} @Bean(name = "ehCacheManager")
public EhCacheManager ehCacheManager(){
EhCacheManager ehCacheManager = new EhCacheManager();
return ehCacheManager;
} @Bean(name = "sessionIdCookie")
public SimpleCookie sessionIdCookie(){
SimpleCookie cookie = new SimpleCookie("sid");
cookie.setHttpOnly(true);
cookie.setMaxAge(-1);//关闭浏览器就过期了 这里也可以设置下过期时间,尽量不重新生成新的sessionId
return cookie;
} @Bean(name = "rememberMeCookie")
public SimpleCookie rememberMeCookie(){
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setHttpOnly(true);
cookie.setPath("/notify");
cookie.setMaxAge(2592000);//30天有效期
return cookie;
} @Bean(name = "rememberMeManager")
public CookieRememberMeManager cookieRememberMeManager(){
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCipherKey(Base64.decode("A7UzJgh1+EWj5oBFi+mSgw=="));
cookieRememberMeManager.setCookie(rememberMeCookie());
return cookieRememberMeManager;
} @Bean
public FormAuthenticationFilter formAuthenticationFilter(){
FormAuthenticationFilter filter = new FormAuthenticationFilter();
filter.setUsernameParam("username");
filter.setPasswordParam("password");
filter.setRememberMeParam("rememberMe");
filter.setLoginUrl("/login");
return filter;
}
编写RedisCacheSessionDAO
public class RedisCacheSessionDAO extends EnterpriseCacheSessionDAO { private static final Logger log = LoggerFactory.getLogger(RedisCacheSessionDAO.class); // Session超时时间,单位为秒
private long expireTime = 3600; @Autowired
private RedisTemplate redisTemplate; public RedisCacheSessionDAO() {
super();
} @Override
protected Serializable doCreate(Session session) {
Serializable sessionId = generateSessionId(session);
assignSessionId(session,sessionId);
redisTemplate.opsForValue().set(sessionId, session, expireTime, TimeUnit.SECONDS);
return sessionId;
} @Override
protected Session doReadSession(Serializable sessionId) {
if(sessionId == null){
return null;
}
//这里一定要在redis拿到session返回,不然在记住账号(remeberMe=true)的情况下一直生成新的session,不记住账号的情况下登录不上session倒是没少生成 单机下这里返回空是没啥问题的
return (Session) redisTemplate.opsForValue().get(sessionId);
} @Override
protected void doUpdate(Session session) {
super.doUpdate(session);
if(session == null){
return;
}
session.setTimeout(expireTime * 1000);
redisTemplate.opsForValue().set(session.getId(), session, expireTime, TimeUnit.SECONDS);
} @Override
protected void doDelete(Session session) {
super.doDelete(session);
if(session == null){
return;
}
redisTemplate.opsForValue().getOperations().delete(session.getId());
} public long getExpireTime() {
return expireTime;
} public void setExpireTime(long expireTime) {
this.expireTime = expireTime;
} public RedisTemplate getRedisTemplate() {
return redisTemplate;
} public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
cipherKey 字符串生成策略 Base64.decode的字符串参数
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128,new SecureRandom("spring-boot-0.0.1".getBytes()));
SecretKey secretKey =keyGenerator.generateKey();
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),"AES");
//cipherKey
System.out.println(new String(Base64.encode(secretKeySpec.getEncoded())));
springboot shiro ehcache redis 简单使用的更多相关文章
- 修改记录-优化后(springboot+shiro+session+redis+ngnix共享)
1.普通用户实现redis共享session 1.配置 #cache指定缓存类型 spring.cache.type=REDIS #data-redis spring.redis.database=1 ...
- SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中
在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...
- springboot之集成mybatis mongo shiro druid redis jsp
闲来无事,研究一下spingboot 发现好多地方都不一样了,第一个就是官方默认不支持jsp 于是开始狂找资料 终于让我找到了 首先引入依赖如下: <!-- tomcat的支持.--> ...
- SpringBoot+Shiro+Redis共享Session入门小栗子
在单机版的Springboot+Shiro的基础上,这次实现共享Session. 这里没有自己写RedisManager.SessionDAO.用的 crazycake 写的开源插件 pom.xml ...
- springboot+shiro+redis(单机redis版)整合教程-续(添加动态角色权限控制)
相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3. springboot+shiro+redis(集群re ...
- springboot+shiro+redis(集群redis版)整合教程
相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3.springboot+shiro+redis(单机red ...
- springboot+shiro+redis(单机redis版)整合教程
相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(集群redis版)整合教程 3.springboot+shiro+redis(单机red ...
- Shiro经过Redis管理会话实现集群(转载)
原文:http://www.myexception.cn/software-architecture-design/1815507.html Shiro通过Redis管理会话实现集群 写在前面 1.在 ...
- 由浅入深学习springboot中使用redis
很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...
随机推荐
- 使用NtQueryInformationFile函数获得不到完整路径
#include <windows.h> #include <iostream> using namespace std; typedef struct _OBJECT_NAM ...
- luogu P4219 [BJOI2014]大融合
题解:原来LCT也能维护子树信息,我太Naive了 用LCT维护当前子树节点个数 具体做法维护siz[x]=当前Splay子树和指向当前Splay子树的虚边所代表的节点个数 auxsiz[x]=指向x ...
- 三分钟入坑指北 🔜 Docsify + Serverless Framework 快速创建个人博客系统
之前由于学摄影的关系,为了提高自己的审美,顺便锻炼下自己的英文能力,翻译了不少国外艺术类的 文章.最近一直想搭一个个人博客来存放这些内容,又懒得折腾建站,遂一直搁置. 直到偶然发现了 docsify ...
- handler method 参数绑定常用注解
handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类: A.处理requet uri 部分(这里指uri template中variable,不含q ...
- 题解 P2622 【关灯问题II】
题目 感觉大佬们的代码在读入上的处理比本蒟蒻优秀多了,于是,一个AFO蒟蒻弱弱地提出一下自己的看法 [分析] 首先,对于 \(n\) 那么小,肯定是状压啦 对于读入,本蒟蒻开了两个数组来储存每个按钮的 ...
- E - Apple Tree POJ - 2486
E - Apple Tree POJ - 2486 Wshxzt is a lovely girl. She likes apple very much. One day HX takes her t ...
- 安装eclipse步骤以及配置jdk
1.官网下载eclipse 2.下载jdk并且安装,记住自己安装路径 3.配置jdk环境变量 在高级系统设置里面配置 新建: 用户变量:“变量名”:JAVA_HOME “变量值”:C:\Program ...
- jboss的JVMroute记录
jboss5的nodename是在 /usr/local/jboss-5.1.0.GA/server/dms/deploy/jbossweb.sar/server.xml 这里的 jvmrout ...
- tensorflow 损失计算--MSN
1.tf.losses.mean_squared_error函数 tf.losses.mean_squared_error( labels, predictions, weights=1.0, sco ...
- JavaScript学习总结(五)
之前的几讲中我们曾经说过,JavaScript中是没有类的概念的.但是我们讲过对象,那么这个对象是怎么来的呢? 只要有函数即可创建对象 自定义对象 自定义对象的方式: 1. 使用无参的函数创建对象 & ...