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=true
spring.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> -->
<!--<!– rollingPolicy:當發生滾動時,決定 RollingFileAppender 的行爲,涉及文件移動和重命名。 –>-->
<!--<!– TimeBasedRollingPolicy: 最常用的滾動策略,它根據時間來制定滾動策略,既負責滾動也負責出發滾動 –>-->
<!--<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<!--<!– 活動文件的名字會根據fileNamePattern的值,每隔一段時間改變一次 –>-->
<!--<!– 文件名:log/demo.2017-12-05.0.log –>-->
<!--<fileNamePattern>/log/wanmo-service.%d.%i.log</fileNamePattern> -->
<!--<!– 每產生一個日誌文件,該日誌文件的保存期限爲30天 –> -->
<!--<maxHistory>30</maxHistory> -->
<!--<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> -->
<!--<!– maxFileSize:這是活動文件的大小,默認值是10MB,測試時可改成1KB看效果 –> -->
<!--<maxFileSize>10MB</maxFileSize> -->
<!--</timeBasedFileNamingAndTriggeringPolicy> -->
<!--</rollingPolicy> -->
<!--<encoder> -->
<!--<!– pattern節點,用來設置日誌的輸入格式 –>-->
<!--<pattern> -->
<!--%d %p (%file:%line\)- %m%n -->
<!--</pattern> -->
<!--<!– 記錄日誌的編碼:此處設置字符集 - –>-->
<!--<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{
@Autowired
private UserMapper userMapper;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("權限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
// TODO Auto-generated method stub
System.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;
@Bean
public RedisManager redisManager(){
RedisManager redisManager = new RedisManager(); // crazycake 實現
// RedisClusterManager redisClusterManager = new RedisClusterManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(180000);
return redisManager;
}
@Bean
public JavaUuidSessionIdGenerator sessionIdGenerator(){
return new JavaUuidSessionIdGenerator();
}
@Bean
public RedisSessionDAO sessionDAO(){
RedisSessionDAO sessionDAO = new RedisSessionDAO(); // crazycake 實現
sessionDAO.setRedisManager(redisManager());
sessionDAO.setSessionIdGenerator(sessionIdGenerator()); // Session ID 生成器
return sessionDAO;
}
@Bean
public SimpleCookie cookie(){
SimpleCookie cookie = new SimpleCookie("SHAREJSESSIONID"); // cookie的name,對應的默認是 JSESSIONID
cookie.setHttpOnly(true);
cookie.setPath("/"); // path爲 / 用於多個系統共享JSESSIONID
return cookie;
}
@Bean
public DefaultWebSessionManager sessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setGlobalSessionTimeout(-1000L); // 設置session超時
sessionManager.setDeleteInvalidSessions(true); // 刪除無效session
sessionManager.setSessionIdCookie(cookie()); // 設置JSESSIONID
sessionManager.setSessionDAO(sessionDAO()); // 設置sessionDAO
return sessionManager;
}
/**
* 1. 配置SecurityManager
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm()); // 設置realm
securityManager.setSessionManager(sessionManager()); // 設置sessionManager
securityManager.setCacheManager(redisCacheManager()); // 配置緩存的話,退出登錄的時候crazycake會報錯,要求放在session裏面的實體類必須有個id標識
return securityManager;
}
/**
* 2. 配置緩存
* @return
*/
// @Bean
// public CacheManager cacheManager(){
// EhCacheManager ehCacheManager = new EhCacheManager();
// ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
// return ehCacheManager;
// }
@Bean
public RedisCacheManager redisCacheManager(){
RedisCacheManager cacheManager = new RedisCacheManager(); // crazycake 實現
cacheManager.setRedisManager(redisManager());
return cacheManager;
}
/**
* 3. 配置Realm
* @return
*/
@Bean
public AuthorizingRealm realm(){
return new UserRealm();
}
/**
* 4. 配置LifecycleBeanPostProcessor,可以來自動的調用配置在Spring IOC容器中 Shiro Bean 的生命週期方法
* @return
*/
@Bean
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
/**
* 5. 啓用IOC容器中使用Shiro的註解,但是必須配置第四步纔可以使用
* @return
*/
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
/**
* 6. 配置ShiroFilter
* @return
*/
@Bean
public 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();
// 配置SecurityManager
factoryBean.setSecurityManager(securityManager());
// 配置權限路徑
factoryBean.setFilterChainDefinitionMap(map);
// 配置登錄url
factoryBean.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 {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("權限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
return authorizationInfo;
}
@Override
protected 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;
@Bean
public RedisManager redisManager(){
RedisManager redisManager = new RedisManager(); // 實現
// RedisClusterManager redisClusterManager = new RedisClusterManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(180000);
return redisManager;
}
@Bean
public JavaUuidSessionIdGenerator sessionIdGenerator(){
return new JavaUuidSessionIdGenerator();
}
@Bean
public RedisSessionDAO sessionDAO(){
RedisSessionDAO sessionDAO = new RedisSessionDAO(); // crazycake 實現
sessionDAO.setRedisManager(redisManager());
sessionDAO.setSessionIdGenerator(sessionIdGenerator()); // Session ID 生成器
return sessionDAO;
}
@Bean
public SimpleCookie cookie(){
SimpleCookie cookie = new SimpleCookie("SHAREJSESSIONID"); // cookie的name,對應的默認是 JSESSIONID
cookie.setHttpOnly(true);
cookie.setPath("/"); // path爲 / 用於多個系統共享JSESSIONID
return cookie;
}
@Bean
public DefaultWebSessionManager sessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setGlobalSessionTimeout(-1000L); // 設置session超時
sessionManager.setDeleteInvalidSessions(true); // 刪除無效session
sessionManager.setSessionIdCookie(cookie()); // 設置JSESSIONID
sessionManager.setSessionDAO(sessionDAO()); // 設置sessionDAO
return sessionManager;
}
/**
* 1. 配置SecurityManager
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm()); // 設置realm
securityManager.setSessionManager(sessionManager()); // 設置sessionManager
securityManager.setCacheManager(redisCacheManager()); // 配置緩存的話,退出登錄的時候crazycake會報錯,要求放在session裏面的實體類必須有個id標識
return securityManager;
}
/**
* 2. 配置緩存
* @return
*/
// @Bean
// public CacheManager cacheManager(){
// EhCacheManager ehCacheManager = new EhCacheManager();
// ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
// return ehCacheManager;
// }
@Bean
public RedisCacheManager redisCacheManager(){
RedisCacheManager cacheManager = new RedisCacheManager(); // crazycake 實現
cacheManager.setRedisManager(redisManager());
return cacheManager;
}
/**
* 3. 配置Realm
* @return
*/
@Bean
public AuthorizingRealm realm(){
return new UserRealm();
}
/**
* 4. 配置LifecycleBeanPostProcessor,可以來自動的調用配置在Spring IOC容器中 Shiro Bean 的生命週期方法
* @return
*/
@Bean
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
/**
* 5. 啓用IOC容器中使用Shiro的註解,但是必須配置第四步纔可以使用
* @return
*/
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
/**
* 6. 配置ShiroFilter
* @return
*/
@Bean
public 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();
// 配置SecurityManager
factoryBean.setSecurityManager(securityManager());
// 配置權限路徑
factoryBean.setFilterChainDefinitionMap(map);
// 配置登錄url
factoryBean.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;
}