引入相关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 简单使用的更多相关文章

  1. 修改记录-优化后(springboot+shiro+session+redis+ngnix共享)

    1.普通用户实现redis共享session 1.配置 #cache指定缓存类型 spring.cache.type=REDIS #data-redis spring.redis.database=1 ...

  2. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  3. springboot之集成mybatis mongo shiro druid redis jsp

    闲来无事,研究一下spingboot  发现好多地方都不一样了,第一个就是官方默认不支持jsp  于是开始狂找资料  终于让我找到了 首先引入依赖如下: <!-- tomcat的支持.--> ...

  4. SpringBoot+Shiro+Redis共享Session入门小栗子

    在单机版的Springboot+Shiro的基础上,这次实现共享Session. 这里没有自己写RedisManager.SessionDAO.用的 crazycake 写的开源插件 pom.xml ...

  5. springboot+shiro+redis(单机redis版)整合教程-续(添加动态角色权限控制)

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3. springboot+shiro+redis(集群re ...

  6. springboot+shiro+redis(集群redis版)整合教程

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3.springboot+shiro+redis(单机red ...

  7. springboot+shiro+redis(单机redis版)整合教程

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(集群redis版)整合教程 3.springboot+shiro+redis(单机red ...

  8. Shiro经过Redis管理会话实现集群(转载)

    原文:http://www.myexception.cn/software-architecture-design/1815507.html Shiro通过Redis管理会话实现集群 写在前面 1.在 ...

  9. 由浅入深学习springboot中使用redis

    很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...

随机推荐

  1. ORACLE常见问题收集

    1.Java代码执行oracle,update和insert语句卡住不动 解决方法:造成这样的情况原因在于你之前执行了update或insert操作但你并没有commit,导致你操作的这条记录被ora ...

  2. DRF框架之序列化器初体验

    首先,我们需要明白序列化和反序列化的过程指的是什么. 序列化操作:将模型数据 ---> 字典数据 --->JSON数据(响应JSON数据的操作) 反序列化操作:将JSON数据 ---> ...

  3. Python Learning Day5

    Response响应 import requests response = requests.get('https://baidu.com') # response响应 print(response. ...

  4. html标签title属性效果优化

    html标签title属性效果不友好,最致命的是响应慢,体验不好,JQuery-UI提供了很好的支持.在jquery.tip的基础上又做了修改,这样子定制效果更强. 代码如下: <!DOCTYP ...

  5. autorclone使用心得

    一边使用一边更新. 0x00  SAs最坑的那地方在于,当我新建了一个group,却只能每天添加100个SAs.但是autorclone在本地调用的SAs却有500个,这样每次copy的时候,auto ...

  6. 到头来还是逃不过Java - 流程控制

    流程控制 没有特殊说明,我的所有这个系列的Java13的笔记都是从廖老师那里摘抄.总结过来的,侵删 引言 兜兜转转到了大四,学过了C,C++,C#,Java,Python,学一门丢一门,到了最后还是要 ...

  7. What is the maximum length of a URL in different browsers?

    https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers ...

  8. python 手动安装模块

    python中 openpyxl是解析 excel 文件的模块,一般使用pip install openpyxl 就可以安装. 但是如果处于公司内网时是无法连网安装的,下面就手动安装进行说明: 1.h ...

  9. JS—Function类型

    1.函数的声明方式有三种普通函数的声明方式function box(num1,num2){ return num1+num2;}alert(box(1,2)); 使用变量初始化函数var box = ...

  10. 前端快速构建神器vue-cli,windows下安装并且构建前端项目

    1.nodejs官网http://nodejs.cn/下载安装包,傻瓜式安装即可 2.dos命令查询node的版本 node -v 查询版本号 npm -v 查询npm包管理版本 3.安装国内镜像 n ...