題解 貪玩藍月
阿新 • • 發佈:2020-08-07
一、前言
本文小編將基於SpringBoot整合Shiro實現動態uri許可權,由前端vue在頁面配置uri,Java後端動態重新整理許可權,不用重啟專案,以及在頁面分配給使用者角色、按鈕、uri許可權後,後端動態分配許可權,使用者無需在頁面重新登入才能獲取最新許可權,一切許可權動態載入,靈活配置
基本環境
- spring-boot 2.1.7
- mybatis-plus 2.1.0
- mysql 5.7.24
- redis 5.0.5
溫馨小提示:案例demo原始碼附文章末尾,有需要的小夥伴們可參考哦 ~
二、SpringBoot整合Shiro
1、引入相關maven依賴
<properties>
<shiro-spring.version>1.4.0</shiro-spring.version>
<shiro-redis.version>3.1.0</shiro-redis.version>
</properties>
<dependencies>
<!-- AOP依賴,一定要加,否則許可權攔截驗證不生效 【注:系統日記也需要此依賴】 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<!-- Shiro 核心依賴 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro-spring.version}</version>
</dependency>
<!-- Shiro-redis外掛 -->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>${shiro-redis.version}</version>
</dependency>
</dependencies>
2、自定義Realm
doGetAuthenticationInfo
:身份認證 (主要是在登入時的邏輯處理)doGetAuthorizationInfo
:登陸認證成功後的處理 ex: 賦予角色和許可權【 注:使用者進行許可權驗證時 Shiro會去快取中找,如果查不到資料,會執行doGetAuthorizationInfo這個方法去查許可權,並放入快取中 】
-> 因此我們在前端頁面分配使用者許可權時 執行清除shiro快取的方法即可實現動態分配使用者許可權
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public String getName() {
return "shiroRealm";
}
/**
* 賦予角色和許可權:使用者進行許可權驗證時 Shiro會去快取中找,如果查不到資料,會執行這個方法去查許可權,並放入快取中
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 獲取使用者
User user = (User) principalCollection.getPrimaryPrincipal();
Integer userId =user.getId();
// 這裡可以進行授權和處理
Set<String> rolesSet = new HashSet<>();
Set<String> permsSet = new HashSet<>();
// 獲取當前使用者對應的許可權(這裡根據業務自行查詢)
List<Role> roleList = roleMapper.selectRoleByUserId( userId );
for (Role role:roleList) {
rolesSet.add( role.getCode() );
List<Menu> menuList = menuMapper.selectMenuByRoleId( role.getId() );
for (Menu menu :menuList) {
permsSet.add( menu.getResources() );
}
}
//將查到的許可權和角色分別傳入authorizationInfo中
authorizationInfo.setStringPermissions(permsSet);
authorizationInfo.setRoles(rolesSet);
log.info("--------------- 賦予角色和許可權成功! ---------------");
return authorizationInfo;
}
/**
* 身份認證 - 之後走上面的 授權
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken tokenInfo = (UsernamePasswordToken)authenticationToken;
// 獲取使用者輸入的賬號
String username = tokenInfo.getUsername();
// 獲取使用者輸入的密碼
String password = String.valueOf( tokenInfo.getPassword() );
// 通過username從資料庫中查詢 User物件,如果找到進行驗證
// 實際專案中,這裡可以根據實際情況做快取,如果不做,Shiro自己也是有時間間隔機制,2分鐘內不會重複執行該方法
User user = userMapper.selectUserByUsername(username);
// 判斷賬號是否存在
if (user == null) {
//返回null -> shiro就會知道這是使用者不存在的異常
return null;
}
// 驗證密碼 【注:這裡不採用shiro自身密碼驗證 , 採用的話會導致使用者登入密碼錯誤時,已登入的賬號也會自動下線! 如果採用,移除下面的清除快取到登入處 處理】
if ( !password.equals( user.getPwd() ) ){
throw new IncorrectCredentialsException("使用者名稱或者密碼錯誤");
}
// 判斷賬號是否被凍結
if (user.getFlag()==null|| "0".equals(user.getFlag())){
throw new LockedAccountException();
}
/**
* 進行驗證 -> 注:shiro會自動驗證密碼
* 引數1:principal -> 放物件就可以在頁面任意地方拿到該物件裡面的值
* 引數2:hashedCredentials -> 密碼
* 引數3:credentialsSalt -> 設定鹽值
* 引數4:realmName -> 自定義的Realm
*/
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
// 驗證成功開始踢人(清除快取和Session)
ShiroUtils.deleteCache(username,true);
// 認證成功後更新token
String token = ShiroUtils.getSession().getId().toString();
user.setToken( token );
userMapper.updateById(user);
return authenticationInfo;
}
}
3、Shiro配置類
@Configuration
public class ShiroConfig {
private final String CACHE_KEY = "shiro:cache:";
private final String SESSION_KEY = "shiro:session:";
/**
* 預設過期時間30分鐘,即在30分鐘內不進行操作則清空快取資訊,頁面即會提醒重新登入
*/
private final int EXPIRE = 1800;
/**
* Redis配置
*/
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
// @Value("${spring.redis.password}")
// private String password;
/**
* 開啟Shiro-aop註解支援:使用代理方式所以需要開啟程式碼支援
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
/**
* Shiro基礎配置
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 自定義過濾器
Map<String, Filter> filtersMap = new LinkedHashMap<>();
// 定義過濾器名稱 【注:map裡面key值對於的value要為authc才能使用自定義的過濾器】
filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() );
filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() );
filtersMap.put( "token", new TokenCheckFilter() );
shiroFilterFactoryBean.setFilters(filtersMap);
// 登入的路徑: 如果你沒有登入則會跳到這個頁面中 - 如果沒有設定值則會預設跳轉到工程根目錄下的"/login.jsp"頁面 或 "/login" 對映
shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
// 登入成功後跳轉的主頁面 (這裡沒用,前端vue控制了跳轉)
// shiroFilterFactoryBean.setSuccessUrl("/index");
// 設定沒有許可權時跳轉的url
shiroFilterFactoryBean.setUnauthorizedUrl("/api/auth/unauth");
shiroFilterFactoryBean.setFilterChainDefinitionMap( shiroConfig.loadFilterChainDefinitionMap() );
return shiroFilterFactoryBean;
}
/**
* 安全管理器
*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 自定義session管理
securityManager.setSessionManager(sessionManager());
// 自定義Cache實現快取管理
securityManager.setCacheManager(cacheManager());
// 自定義Realm驗證
securityManager.setRealm(shiroRealm());
return securityManager;
}
/**
* 身份驗證器
*/
@Bean
public ShiroRealm shiroRealm() {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
/**
* 自定義Realm的加密規則 -> 憑證匹配器:將密碼校驗交給Shiro的SimpleAuthenticationInfo進行處理,在這裡做匹配配置
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
// 雜湊演算法:這裡使用SHA256演算法;
shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
// 雜湊的次數,比如雜湊兩次,相當於 md5(md5(""));
shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS);
return shaCredentialsMatcher;
}
/**
* 配置Redis管理器:使用的是shiro-redis開源外掛
*/
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
return redisManager;
}
/**
* 配置Cache管理器:用於往Redis儲存許可權和角色標識 (使用的是shiro-redis開源外掛)
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
redisCacheManager.setKeyPrefix(CACHE_KEY);
// 配置快取的話要求放在session裡面的實體類必須有個id標識 注:這裡id為使用者表中的主鍵,否-> 報:User must has getter for field: xx
redisCacheManager.setPrincipalIdFieldName("id");
return redisCacheManager;
}
/**
* SessionID生成器
*/
@Bean
public ShiroSessionIdGenerator sessionIdGenerator(){
return new ShiroSessionIdGenerator();
}
/**
* 配置RedisSessionDAO (使用的是shiro-redis開源外掛)
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setSessionIdGenerator(sessionIdGenerator());
redisSessionDAO.setKeyPrefix(SESSION_KEY);
redisSessionDAO.setExpire(EXPIRE);
return redisSessionDAO;
}
/**
* 配置Session管理器
*/
@Bean
public SessionManager sessionManager() {
ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
shiroSessionManager.setSessionDAO(redisSessionDAO());
return shiroSessionManager;
}
}
三、shiro動態載入許可權處理方法
loadFilterChainDefinitionMap
:初始化許可權
ex: 在上面Shiro配置類ShiroConfig
中的Shiro基礎配置shiroFilterFactory
方法中我們就需要呼叫此方法將資料庫中配置的所有uri許可權全部載入進去,以及放行介面和配置許可權過濾器等【注:過濾器配置順序不能顛倒,多個過濾器用
,分割】
ex:filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
updatePermission
:動態重新整理載入資料庫中的uri許可權 -> 頁面在新增uri路徑到資料庫中,也就是配置新的許可權時就可以呼叫此方法實現動態載入uri許可權updatePermissionByRoleId
:shiro動態許可權載入 -> 即分配指定使用者許可權時可呼叫此方法刪除shiro快取,重新執行doGetAuthorizationInfo
方法授權角色和許可權
public interface ShiroService {
/**
* 初始化許可權 -> 拿全部許可權
*
* @param :
* @return: java.util.Map<java.lang.String,java.lang.String>
*/
Map<String, String> loadFilterChainDefinitionMap();
/**
* 在對uri許可權進行增刪改操作時,需要呼叫此方法進行動態重新整理載入資料庫中的uri許可權
*
* @param shiroFilterFactoryBean
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
/**
* shiro動態許可權載入 -> 原理:刪除shiro快取,重新執行doGetAuthorizationInfo方法授權角色和許可權
*
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession);
}
@Slf4j
@Service
public class ShiroServiceImpl implements ShiroService {
@Autowired
private MenuMapper menuMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public Map<String, String> loadFilterChainDefinitionMap() {
// 許可權控制map
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 配置過濾:不會被攔截的連結 -> 放行 start ----------------------------------------------------------
// 放行Swagger2頁面,需要放行這些
filterChainDefinitionMap.put("/swagger-ui.html","anon");
filterChainDefinitionMap.put("/swagger/**","anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/swagger-resources/**","anon");
filterChainDefinitionMap.put("/v2/**","anon");
filterChainDefinitionMap.put("/static/**", "anon");
// 登陸
filterChainDefinitionMap.put("/api/auth/login/**", "anon");
// 三方登入
filterChainDefinitionMap.put("/api/auth/loginByQQ", "anon");
filterChainDefinitionMap.put("/api/auth/afterlogin.do", "anon");
// 退出
filterChainDefinitionMap.put("/api/auth/logout", "anon");
// 放行未授權介面,重定向使用
filterChainDefinitionMap.put("/api/auth/unauth", "anon");
// token過期介面
filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
// 被擠下線
filterChainDefinitionMap.put("/api/auth/downline", "anon");
// 放行 end ----------------------------------------------------------
// 從資料庫或快取中查取出來的url與resources對應則不會被攔截 放行
List<Menu> permissionList = menuMapper.selectList( null );
if ( !CollectionUtils.isEmpty( permissionList ) ) {
permissionList.forEach( e -> {
if ( StringUtils.isNotBlank( e.getUrl() ) ) {
// 根據url查詢相關聯的角色名,拼接自定義的角色許可權
List<Role> roleList = roleMapper.selectRoleByMenuId( e.getId() );
StringJoiner zqRoles = new StringJoiner(",", "zqRoles[", "]");
if ( !CollectionUtils.isEmpty( roleList ) ){
roleList.forEach( f -> {
zqRoles.add( f.getCode() );
});
}
// 注意過濾器配置順序不能顛倒
// ① 認證登入
// ② 認證自定義的token過濾器 - 判斷token是否有效
// ③ 角色許可權 zqRoles:自定義的只需要滿足其中一個角色即可訪問 ; roles[admin,guest] : 預設需要每個引數滿足才算通過,相當於hasAllRoles()方法
// ④ zqPerms:認證自定義的url過濾器攔截許可權 【注:多個過濾器用 , 分割】
// filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,roles[admin,guest],zqPerms[" + e.getResources() + "]" );
filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,"+ zqRoles.toString() +",zqPerms[" + e.getResources() + "]" );
// filterChainDefinitionMap.put("/api/system/user/listPage", "authc,token,zqPerms[user1]"); // 寫死的一種用法
}
});
}
// ⑤ 認證登入 【注:map不能存放相同key】
filterChainDefinitionMap.put("/**", "authc");
return filterChainDefinitionMap;
}
@Override
public void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession) {
synchronized (this) {
AbstractShiroFilter shiroFilter;
try {
shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
} catch (Exception e) {
throw new MyException("get ShiroFilter from shiroFilterFactoryBean error!");
}
PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
// 清空攔截管理器中的儲存
manager.getFilterChains().clear();
// 清空攔截工廠中的儲存,如果不清空這裡,還會把之前的帶進去
// ps:如果僅僅是更新的話,可以根據這裡的 map 遍歷資料修改,重新整理好許可權再一起新增
shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
// 動態查詢資料庫中所有許可權
shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitionMap());
// 重新構建生成攔截
Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
for (Map.Entry<String, String> entry : chains.entrySet()) {
manager.createChain(entry.getKey(), entry.getValue());
}
log.info("--------------- 動態生成url許可權成功! ---------------");
// 動態更新該角色相關聯的使用者shiro許可權
if(roleId != null){
updatePermissionByRoleId(roleId,isRemoveSession);
}
}
}
@Override
public void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession) {
// 查詢當前角色的使用者shiro快取資訊 -> 實現動態許可權
List<User> userList = userMapper.selectUserByRoleId(roleId);
// 刪除當前角色關聯的使用者快取資訊,使用者再次訪問介面時會重新授權 ; isRemoveSession為true時刪除Session -> 即強制使用者退出
if ( !CollectionUtils.isEmpty( userList ) ) {
for (User user : userList) {
ShiroUtils.deleteCache(user.getUsername(), isRemoveSession);
}
}
log.info("--------------- 動態修改使用者許可權成功! ---------------");
}
}
四、shiro中自定義角色、許可權過濾器
1、自定義uri許可權過濾器zqPerms
@Slf4j
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String requestUrl = httpRequest.getServletPath();
log.info("請求的url: " + requestUrl);
// 檢查是否擁有訪問許可權
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
// 轉換成http的請求和響應
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 獲取請求頭的值
String header = req.getHeader("X-Requested-With");
// ajax 的請求頭裡有X-Requested-With: XMLHttpRequest 正常請求沒有
if (header!=null && "XMLHttpRequest".equals(header)){
resp.setContentType("text/json,charset=UTF-8");
resp.getWriter().print("{\"success\":false,\"msg\":\"沒有許可權操作!\"}");
}else { //正常請求
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}
}
2、自定義角色許可權過濾器zqRoles
shiro原生的角色過濾器RolesAuthorizationFilter 預設是必須同時滿足roles[admin,guest]
才有許可權,而自定義的zqRoles
只滿足其中一個即可訪問
ex:zqRoles[admin,guest]
public class MyRolesAuthorizationFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
Subject subject = getSubject(req, resp);
String[] rolesArray = (String[]) mappedValue;
// 沒有角色限制,有許可權訪問
if (rolesArray == null || rolesArray.length == 0) {
return true;
}
for (int i = 0; i < rolesArray.length; i++) {
//若當前使用者是rolesArray中的任何一個,則有許可權訪問
if (subject.hasRole(rolesArray[i])) {
return true;
}
}
return false;
}
}
3、自定義token過濾器token
-> 判斷token是否過期失效等
@Slf4j
public class TokenCheckFilter extends UserFilter {
/**
* token過期、失效
*/
private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";
/**
* 判斷是否擁有許可權 true:認證成功 false:認證失敗
* mappedValue 訪問該url時需要的許可權
* subject.isPermitted 判斷訪問的使用者是否擁有mappedValue許可權
*/
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 根據請求頭拿到token
String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);
log.info("瀏覽器token:" + token );
User userInfo = ShiroUtils.getUserInfo();
String userToken = userInfo.getToken();
// 檢查token是否過期
if ( !token.equals(userToken) ){
return false;
}
return true;
}
/**
* 認證失敗回撥的方法: 如果登入實體為null就儲存請求和跳轉登入頁面,否則就跳轉無許可權配置頁面
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
User userInfo = ShiroUtils.getUserInfo();
// 重定向錯誤提示處理 - 前後端分離情況下
WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
return false;
}
}
五、專案中會用到的一些工具類、常量等
溫馨小提示:這裡只是部分,詳情可參考文章末尾給出的案例demo原始碼
1、Shiro工具類
public class ShiroUtils {
/** 私有構造器 **/
private ShiroUtils(){ }
private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);
/**
* 獲取當前使用者Session
* @Return SysUserEntity 使用者資訊
*/
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
/**
* 使用者登出
*/
public static void logout() {
SecurityUtils.getSubject().logout();
}
/**
* 獲取當前使用者資訊
* @Return SysUserEntity 使用者資訊
*/
public static User getUserInfo() {
return (User) SecurityUtils.getSubject().getPrincipal();
}
/**
* 刪除使用者快取資訊
* @Param username 使用者名稱稱
* @Param isRemoveSession 是否刪除Session,刪除後用戶需重新登入
*/
public static void deleteCache(String username, boolean isRemoveSession){
//從快取中獲取Session
Session session = null;
// 獲取當前已登入的使用者session列表
Collection<Session> sessions = redisSessionDAO.getActiveSessions();
User sysUserEntity;
Object attribute = null;
// 遍歷Session,找到該使用者名稱稱對應的Session
for(Session sessionInfo : sessions){
attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (attribute == null) {
continue;
}
sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
if (sysUserEntity == null) {
continue;
}
if (Objects.equals(sysUserEntity.getUsername(), username)) {
session=sessionInfo;
// 清除該使用者以前登入時儲存的session,強制退出 -> 單使用者登入處理
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
}
}
if (session == null||attribute == null) {
return;
}
//刪除session
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
//刪除Cache,再訪問受限介面時會重新授權
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
Authenticator authc = securityManager.getAuthenticator();
((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
}
/**
* 從快取中獲取指定使用者名稱的Session
* @param username
*/
private static Session getSessionByUsername(String username){
// 獲取當前已登入的使用者session列表
Collection<Session> sessions = redisSessionDAO.getActiveSessions();
User user;
Object attribute;
// 遍歷Session,找到該使用者名稱稱對應的Session
for(Session session : sessions){
attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (attribute == null) {
continue;
}
user = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
if (user == null) {
continue;
}
if (Objects.equals(user.getUsername(), username)) {
return session;
}
}
return null;
}
}
2、Redis常量類
public interface RedisConstant {
/**
* TOKEN字首
*/
String REDIS_PREFIX_LOGIN = "code-generator_token_%s";
}
3、Spring上下文工具類
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Spring在bean初始化後會判斷是不是ApplicationContextAware的子類
* 如果該類是,setApplicationContext()方法,會將容器中ApplicationContext作為引數傳入進去
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 通過Name返回指定的Bean
*/
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}