springboot shiro 使用redis存储登录信息 实现单点登录sso

本文主要是介绍springboot shiro 使用redis存储登录信息 实现单点登录sso,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

shiro 默认使用的是session 存储登录信息的,这对于单体应用来讲是没有什么问题的,但是对于分布式应用或者集群应用就行不通了,因为集群或者分布式系统 应用部署在不同的jvm 上,session不能共享。如果使用redis存储登录信息则可以解决这个问题,这里简单使用 shiro-redis框架 来实现这个功能

具体流程如下

首先我们创建一个springboot 父子工程 

父工程pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.shiroredis</groupId><artifactId>shiro-redis-sso</artifactId><version>0.0.1-SNAPSHOT</version><name>shiro-redis-sso</name><packaging>pom</packaging><properties><java.version>1.8</java.version></properties><modules><module>user</module><module>other</module></modules><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.29</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-all</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.crazycake</groupId><artifactId>shiro-redis</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

两个子工程pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.shiroredis</groupId><artifactId>shiro-redis-sso</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.shiroredis</groupId><artifactId>user</artifactId><version>0.0.1-SNAPSHOT</version><name>user</name></project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.shiroredis</groupId><artifactId>shiro-redis-sso</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.shiroredis</groupId><artifactId>other</artifactId><version>0.0.1-SNAPSHOT</version><name>other</name></project>

创建数据库  

CREATE DATABASE /*!32312 IF NOT EXISTS*/`ease-run` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `ease-run`;/*Table structure for table `user` */DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`username` varchar(50) DEFAULT NULL,`password` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;/*Data for the table `user` */insert  into `user`(`id`,`username`,`password`) values (1,'yangzheng','123'),(2,'yangzheng1','123'),(3,'yangzheng3','123'),(5,'yangzheng4','1234');

在user模块创建 实体类  mapper  xml 文件

package com.shiroredis.entity;import lombok.Data;import java.io.Serializable;/*** <p>* * </p>** @author Adam* @since 2019-10-04*/
@Data
public class User implements Serializable{private Long id;private String username;private String password;
}
package com.shiroredis.dao;import com.shiroredis.entity.User;public interface UserMapper {User selectUserByUsernameAndPassword(String username,String password);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiroredis.dao.UserMapper"><select id="selectUserByUsernameAndPassword" resultType="com.shiroredis.entity.User">select * from user where username = #{username} and password = #{password}</select></mapper>

user模块配置文件

server.port=8080#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/ease-run?serverTimezone=Asia/Chongqing&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#mybatis-plus
#Mybatis扫描
mybatis.mapper-locations=classpath*:mapper/*.xml
#起别名。可省略写mybatis的xml中的resultType的全路径
mybatis.type-aliases-package=com.shiroredis.entity#druid配置# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000 
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 校验SQL,Oracle配置 spring.datasource.validationQuery=SELECT 1 FROM DUAL,如果不配validationQuery项,则下面三项配置无用
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,logback
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=truespring.redis.host=localhost
spring.redis.port=6379#log
logging.path=./logs
logging.file=Log   
logging.config=classpath:logback-spring-dev.xml

logback日志配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>    <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->    <!-- appender是configuration的子节点,是负责写日志的组件。 --><!-- ConsoleAppender:把日志输出到控制台 --><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d %p (%file:%line\)- %m%n</pattern><!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 --><charset>UTF-8</charset></encoder></appender><!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 --><!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是demo.log --><!--             2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名--><appender name="demolog" class="ch.qos.logback.core.rolling.RollingFileAppender"><!--<File>/log/wanmo-service.log</File>    --><!--&lt;!&ndash; rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 &ndash;&gt;--><!--&lt;!&ndash; TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 &ndash;&gt;--><!--<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">    --><!--&lt;!&ndash; 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 &ndash;&gt;--><!--&lt;!&ndash; 文件名:log/demo.2017-12-05.0.log &ndash;&gt;--><!--<fileNamePattern>/log/wanmo-service.%d.%i.log</fileNamePattern> --><!--&lt;!&ndash; 每产生一个日志文件,该日志文件的保存期限为30天 &ndash;&gt; --><!--<maxHistory>30</maxHistory>   --><!--<timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">    --><!--&lt;!&ndash; maxFileSize:这是活动文件的大小,默认值是10MB,测试时可改成1KB看效果 &ndash;&gt;  --><!--<maxFileSize>10MB</maxFileSize>    --><!--</timeBasedFileNamingAndTriggeringPolicy>    --><!--</rollingPolicy>    --><!--<encoder>    --><!--&lt;!&ndash; pattern节点,用来设置日志的输入格式 &ndash;&gt;--><!--<pattern>    --><!--%d %p (%file:%line\)- %m%n  --><!--</pattern>    --><!--&lt;!&ndash; 记录日志的编码:此处设置字符集 - &ndash;&gt;--><!--<charset>UTF-8</charset>--><!--</encoder>    --></appender>    <!-- 控制台输出日志级别 --><root level="info">    <appender-ref ref="STDOUT" />    </root>    <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 --><!-- com.liyan为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG --><!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  --><logger name="com.yangzheng" level="DEBUG"><appender-ref ref="demolog" />    </logger>    
</configuration>  

shiro realm 类

package com.shiroredis.realm;import com.shiroredis.dao.UserMapper;
import com.shiroredis.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;/*** 自定义realm* @author jianping.lu**/
public class UserRealm extends AuthorizingRealm{@Autowiredprivate UserMapper userMapper;@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();return authorizationInfo;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {// TODO Auto-generated method stubSystem.out.println("认证");//shiro判断逻辑UsernamePasswordToken user = (UsernamePasswordToken) arg0;User newUser = userMapper.selectUserByUsernameAndPassword(user.getUsername(),String.valueOf(user.getPassword()));if(newUser == null){//用户名错误return null;}return new SimpleAuthenticationInfo(newUser,newUser.getPassword(),"");}
}

核心shiroConfig 类

这里将默认的shiro 的 sessionmanager 和cachemanager 换成了  crazycake 基于redis 实现的  sessionmanager 和cachemanager,即可用 redis 管理 登录信息,注意一点是  shiroconfig 如果要使用@Value注解读取配置数据时,需要把

@Bean
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){return new LifecycleBeanPostProcessor();
}

方法改成静态的。

package com.shiroredis.config;import com.shiroredis.realm.UserRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;import java.util.LinkedHashMap;@Configuration
public class ShiroConfig {@Value("${spring.redis.host}")String host;@Value("${spring.redis.port}")int port;@Beanpublic RedisManager redisManager(){RedisManager redisManager = new RedisManager();     // crazycake 实现
//        RedisClusterManager redisClusterManager = new RedisClusterManager();redisManager.setHost(host);redisManager.setPort(port);redisManager.setTimeout(180000);return redisManager;}@Beanpublic JavaUuidSessionIdGenerator sessionIdGenerator(){return new JavaUuidSessionIdGenerator();}@Beanpublic RedisSessionDAO sessionDAO(){RedisSessionDAO sessionDAO = new RedisSessionDAO(); // crazycake 实现sessionDAO.setRedisManager(redisManager());sessionDAO.setSessionIdGenerator(sessionIdGenerator()); //  Session ID 生成器return sessionDAO;}@Beanpublic SimpleCookie cookie(){SimpleCookie cookie = new SimpleCookie("SHAREJSESSIONID"); //  cookie的name,对应的默认是 JSESSIONIDcookie.setHttpOnly(true);cookie.setPath("/");        //  path为 / 用于多个系统共享JSESSIONIDreturn cookie;}@Beanpublic DefaultWebSessionManager sessionManager(){DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();sessionManager.setGlobalSessionTimeout(-1000L);    // 设置session超时sessionManager.setDeleteInvalidSessions(true);      // 删除无效sessionsessionManager.setSessionIdCookie(cookie());            // 设置JSESSIONIDsessionManager.setSessionDAO(sessionDAO());         // 设置sessionDAOreturn sessionManager;}/*** 1. 配置SecurityManager* @return*/@Beanpublic DefaultWebSecurityManager securityManager(){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(realm());  // 设置realmsecurityManager.setSessionManager(sessionManager());    // 设置sessionManagersecurityManager.setCacheManager(redisCacheManager()); // 配置缓存的话,退出登录的时候crazycake会报错,要求放在session里面的实体类必须有个id标识return securityManager;}/*** 2. 配置缓存* @return*/
//    @Bean
//    public CacheManager cacheManager(){
//        EhCacheManager ehCacheManager = new EhCacheManager();
//        ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
//        return ehCacheManager;
//    }@Beanpublic RedisCacheManager redisCacheManager(){RedisCacheManager cacheManager = new RedisCacheManager();   // crazycake 实现cacheManager.setRedisManager(redisManager());return cacheManager;}/*** 3. 配置Realm* @return*/@Beanpublic AuthorizingRealm realm(){return new UserRealm();}/*** 4. 配置LifecycleBeanPostProcessor,可以来自动的调用配置在Spring IOC容器中 Shiro Bean 的生命周期方法* @return*/@Beanpublic static LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){return new LifecycleBeanPostProcessor();}/*** 5. 启用IOC容器中使用Shiro的注解,但是必须配置第四步才可以使用* @return*/@Bean@DependsOn("lifecycleBeanPostProcessor")public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){return new DefaultAdvisorAutoProxyCreator();}/*** 6. 配置ShiroFilter* @return*/@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(){LinkedHashMap<String, String> map = new LinkedHashMap<>();map.put("/user/login", "anon");map.put("/user/logout", "anon");// everything else requires authentication:map.put("/**", "authc");ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();// 配置SecurityManagerfactoryBean.setSecurityManager(securityManager());// 配置权限路径factoryBean.setFilterChainDefinitionMap(map);// 配置登录urlfactoryBean.setLoginUrl("/");// 配置无权限路径factoryBean.setUnauthorizedUrl("/unauthorized");return factoryBean;}}

controller 层

package com.shiroredis.controller;import com.shiroredis.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {@RequestMapping("/login")public User login(@RequestParam(value = "username") String username,@RequestParam(value = "password") String password){Subject subject = SecurityUtils.getSubject();subject.login(new UsernamePasswordToken(username, password));User user = (User) SecurityUtils.getSubject().getPrincipal();return user;}@RequestMapping("/logout")public Boolean logout(){Subject subject = SecurityUtils.getSubject();subject.logout();return true;}@RequestMapping("/get")public User get(){User user = (User) SecurityUtils.getSubject().getPrincipal();return user;}}

user 模块效果

redis  数据

cookie 数据 可以发现和redis的key是一样的

再配置other 模块,这里就比较简单了

@SpringBootApplication 注解换成

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

取消自动注入数据源,因为不需要从数据库读取用户数据了

 

配置文件

server.port=8082
spring.redis.host=localhost
spring.redis.port=6379

 

实体类  直接复制就可以了

package com.shiroredis.entity;import lombok.Data;import java.io.Serializable;/*** <p>* * </p>** @author Adam* @since 2019-10-04*/
@Data
public class User implements Serializable{private Long id;private String username;private String password;
}

realm 要注意删掉  认证方法里面的内容,因为其他模块不需要登录,只要获取登录的用户信息即可

package com.shiroredis.realm;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;/*** 自定义realm** @author jianping.lu*/
public class UserRealm extends AuthorizingRealm {@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();return authorizationInfo;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {return null;}
}

shiroconfig 直接复制就可以了

package com.shiroredis.config;import com.shiroredis.realm.UserRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;import java.util.LinkedHashMap;@Configuration
public class ShiroConfig {@Value("${spring.redis.host}")String host;@Value("${spring.redis.port}")int port;@Beanpublic RedisManager redisManager(){RedisManager redisManager = new RedisManager();     //  实现
//        RedisClusterManager redisClusterManager = new RedisClusterManager();redisManager.setHost(host);redisManager.setPort(port);redisManager.setTimeout(180000);return redisManager;}@Beanpublic JavaUuidSessionIdGenerator sessionIdGenerator(){return new JavaUuidSessionIdGenerator();}@Beanpublic RedisSessionDAO sessionDAO(){RedisSessionDAO sessionDAO = new RedisSessionDAO(); // crazycake 实现sessionDAO.setRedisManager(redisManager());sessionDAO.setSessionIdGenerator(sessionIdGenerator()); //  Session ID 生成器return sessionDAO;}@Beanpublic SimpleCookie cookie(){SimpleCookie cookie = new SimpleCookie("SHAREJSESSIONID"); //  cookie的name,对应的默认是 JSESSIONIDcookie.setHttpOnly(true);cookie.setPath("/");        //  path为 / 用于多个系统共享JSESSIONIDreturn cookie;}@Beanpublic DefaultWebSessionManager sessionManager(){DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();sessionManager.setGlobalSessionTimeout(-1000L);    // 设置session超时sessionManager.setDeleteInvalidSessions(true);      // 删除无效sessionsessionManager.setSessionIdCookie(cookie());            // 设置JSESSIONIDsessionManager.setSessionDAO(sessionDAO());         // 设置sessionDAOreturn sessionManager;}/*** 1. 配置SecurityManager* @return*/@Beanpublic DefaultWebSecurityManager securityManager(){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(realm());  // 设置realmsecurityManager.setSessionManager(sessionManager());    // 设置sessionManagersecurityManager.setCacheManager(redisCacheManager()); // 配置缓存的话,退出登录的时候crazycake会报错,要求放在session里面的实体类必须有个id标识return securityManager;}/*** 2. 配置缓存* @return*/
//    @Bean
//    public CacheManager cacheManager(){
//        EhCacheManager ehCacheManager = new EhCacheManager();
//        ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
//        return ehCacheManager;
//    }@Beanpublic RedisCacheManager redisCacheManager(){RedisCacheManager cacheManager = new RedisCacheManager();   // crazycake 实现cacheManager.setRedisManager(redisManager());return cacheManager;}/*** 3. 配置Realm* @return*/@Beanpublic AuthorizingRealm realm(){return new UserRealm();}/*** 4. 配置LifecycleBeanPostProcessor,可以来自动的调用配置在Spring IOC容器中 Shiro Bean 的生命周期方法* @return*/@Beanpublic static LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){return new LifecycleBeanPostProcessor();}/*** 5. 启用IOC容器中使用Shiro的注解,但是必须配置第四步才可以使用* @return*/@Bean@DependsOn("lifecycleBeanPostProcessor")public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){return new DefaultAdvisorAutoProxyCreator();}/*** 6. 配置ShiroFilter* @return*/@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(){LinkedHashMap<String, String> map = new LinkedHashMap<>();map.put("/user/login", "anon");map.put("/user/logout", "anon");// everything else requires authentication:map.put("/**", "authc");ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();// 配置SecurityManagerfactoryBean.setSecurityManager(securityManager());// 配置权限路径factoryBean.setFilterChainDefinitionMap(map);// 配置登录urlfactoryBean.setLoginUrl("/");// 配置无权限路径factoryBean.setUnauthorizedUrl("/unauthorized");return factoryBean;}}

controller 就不用提供登录,退出登录方法了

package com.shiroredis.controller;import com.shiroredis.entity.User;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {@RequestMapping("/get")public User get(){User user = (User) SecurityUtils.getSubject().getPrincipal();return user;}}

运行效果

有一个地方需要注意,由于shiro-redis使用到了 ThreadLocal,在高并发场景下有可能会造成内存溢出,解决办法是禁用ThreadLocal,shiro-redis版本升级至  3.2.3

<dependency><groupId>org.crazycake</groupId><artifactId>shiro-redis</artifactId><version>3.2.3</version>
</dependency>

shiroConfig  添加   sessionDAO.setSessionInMemoryEnabled(false);  禁用ThreadLocal就可以了

@Bean
public RedisSessionDAO sessionDAO(){RedisSessionDAO sessionDAO = new RedisSessionDAO(); // crazycake 实现sessionDAO.setSessionInMemoryEnabled(false);sessionDAO.setRedisManager(redisManager());sessionDAO.setSessionIdGenerator(sessionIdGenerator()); //  Session ID 生成器return sessionDAO;
}

最后附上源码  https://github.com/Yanyf765/shiro-redis-sso

这篇关于springboot shiro 使用redis存储登录信息 实现单点登录sso的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097317

相关文章

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co