SpringBoot使用Shiro實現(xiàn)動態(tài)加載權(quán)限詳解流程
一、序章
基本環(huán)境
- spring-boot 2.1.7
- mybatis-plus 2.1.0
- mysql 5.7.24
- redis 5.0.5
溫馨小提示:案例demo源碼附文章末尾,有需要的小伙伴們可參考哦 ~
二、SpringBoot集成Shiro
1、引入相關(guān)maven依賴
<properties>
<shiro-spring.version>1.4.0</shiro-spring.version>
<shiro-redis.version>3.1.0</shiro-redis.version>
</properties>
<dependencies>
<!-- AOP依賴,一定要加,否則權(quán)限攔截驗證不生效 【注:系統(tǒng)日記也需要此依賴】 -->
<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:身份認(rèn)證 (主要是在登錄時的邏輯處理)doGetAuthorizationInfo:登陸認(rèn)證成功后的處理 ex: 賦予角色和權(quán)限
【 注:用戶進行權(quán)限驗證時 Shiro會去緩存中找,如果查不到數(shù)據(jù),會執(zhí)行doGetAuthorizationInfo這個方法去查權(quán)限,并放入緩存中 】 -> 因此我們在前端頁面分配用戶權(quán)限時 執(zhí)行清除shiro緩存的方法即可實現(xiàn)動態(tài)分配用戶權(quán)限
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public String getName() {
return "shiroRealm";
}
/**
* 賦予角色和權(quán)限:用戶進行權(quán)限驗證時 Shiro會去緩存中找,如果查不到數(shù)據(jù),會執(zhí)行這個方法去查權(quán)限,并放入緩存中
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 獲取用戶
User user = (User) principalCollection.getPrimaryPrincipal();
Integer userId =user.getId();
// 這里可以進行授權(quán)和處理
Set<String> rolesSet = new HashSet<>();
Set<String> permsSet = new HashSet<>();
// 獲取當(dāng)前用戶對應(yīng)的權(quán)限(這里根據(jù)業(yè)務(wù)自行查詢)
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() );
}
}
//將查到的權(quán)限和角色分別傳入authorizationInfo中
authorizationInfo.setStringPermissions(permsSet);
authorizationInfo.setRoles(rolesSet);
log.info("--------------- 賦予角色和權(quán)限成功! ---------------");
return authorizationInfo;
}
/**
* 身份認(rèn)證 - 之后走上面的 授權(quán)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken tokenInfo = (UsernamePasswordToken)authenticationToken;
// 獲取用戶輸入的賬號
String username = tokenInfo.getUsername();
// 獲取用戶輸入的密碼
String password = String.valueOf( tokenInfo.getPassword() );
// 通過username從數(shù)據(jù)庫中查找 User對象,如果找到進行驗證
// 實際項目中,這里可以根據(jù)實際情況做緩存,如果不做,Shiro自己也是有時間間隔機制,2分鐘內(nèi)不會重復(fù)執(zhí)行該方法
User user = userMapper.selectUserByUsername(username);
// 判斷賬號是否存在
if (user == null) {
//返回null -> shiro就會知道這是用戶不存在的異常
return null;
}
// 驗證密碼 【注:這里不采用shiro自身密碼驗證 , 采用的話會導(dǎo)致用戶登錄密碼錯誤時,已登錄的賬號也會自動下線! 如果采用,移除下面的清除緩存到登錄處 處理】
if ( !password.equals( user.getPwd() ) ){
throw new IncorrectCredentialsException("用戶名或者密碼錯誤");
}
// 判斷賬號是否被凍結(jié)
if (user.getFlag()==null|| "0".equals(user.getFlag())){
throw new LockedAccountException();
}
/**
* 進行驗證 -> 注:shiro會自動驗證密碼
* 參數(shù)1:principal -> 放對象就可以在頁面任意地方拿到該對象里面的值
* 參數(shù)2:hashedCredentials -> 密碼
* 參數(shù)3:credentialsSalt -> 設(shè)置鹽值
* 參數(shù)4:realmName -> 自定義的Realm
*/
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
// 驗證成功開始踢人(清除緩存和Session)
ShiroUtils.deleteCache(username,true);
// 認(rèn)證成功后更新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:";
/**
* 默認(rèn)過期時間30分鐘,即在30分鐘內(nèi)不進行操作則清空緩存信息,頁面即會提醒重新登錄
*/
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基礎(chǔ)配置
*/
@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);
// 登錄的路徑: 如果你沒有登錄則會跳到這個頁面中 - 如果沒有設(shè)置值則會默認(rèn)跳轉(zhuǎn)到工程根目錄下的"/login.jsp"頁面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
// 登錄成功后跳轉(zhuǎn)的主頁面 (這里沒用,前端vue控制了跳轉(zhuǎn))
// shiroFilterFactoryBean.setSuccessUrl("/index");
// 設(shè)置沒有權(quán)限時跳轉(zhuǎn)的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實現(xiàn)緩存管理
securityManager.setCacheManager(cacheManager());
// 自定義Realm驗證
securityManager.setRealm(shiroRealm());
return securityManager;
}
/**
* 身份驗證器
*/
@Bean
public ShiroRealm shiroRealm() {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
/**
* 自定義Realm的加密規(guī)則 -> 憑證匹配器:將密碼校驗交給Shiro的SimpleAuthenticationInfo進行處理,在這里做匹配配置
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
// 散列算法:這里使用SHA256算法;
shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
// 散列的次數(shù),比如散列兩次,相當(dāng)于 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存儲權(quán)限和角色標(biāo)識 (使用的是shiro-redis開源插件)
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
redisCacheManager.setKeyPrefix(CACHE_KEY);
// 配置緩存的話要求放在session里面的實體類必須有個id標(biāo)識 注:這里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動態(tài)加載權(quán)限處理方法
loadFilterChainDefinitionMap:初始化權(quán)限
ex: 在上面Shiro配置類ShiroConfig中的Shiro基礎(chǔ)配置shiroFilterFactory方法中我們就需要調(diào)用此方法將數(shù)據(jù)庫中配置的所有uri權(quán)限全部加載進去,以及放行接口和配置權(quán)限過濾器等
【注:過濾器配置順序不能顛倒,多個過濾器用,分割】
ex: filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
updatePermission:動態(tài)刷新加載數(shù)據(jù)庫中的uri權(quán)限 -> 頁面在新增uri路徑到數(shù)據(jù)庫中,也就是配置新的權(quán)限時就可以調(diào)用此方法實現(xiàn)動態(tài)加載uri權(quán)限
updatePermissionByRoleId:shiro動態(tài)權(quán)限加載 -> 即分配指定用戶權(quán)限時可調(diào)用此方法刪除shiro緩存,重新執(zhí)行doGetAuthorizationInfo方法授權(quán)角色和權(quán)限
public interface ShiroService {
/**
* 初始化權(quán)限 -> 拿全部權(quán)限
*
* @param :
* @return: java.util.Map<java.lang.String,java.lang.String>
*/
Map<String, String> loadFilterChainDefinitionMap();
/**
* 在對uri權(quán)限進行增刪改操作時,需要調(diào)用此方法進行動態(tài)刷新加載數(shù)據(jù)庫中的uri權(quán)限
*
* @param shiroFilterFactoryBean
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
/**
* shiro動態(tài)權(quán)限加載 -> 原理:刪除shiro緩存,重新執(zhí)行doGetAuthorizationInfo方法授權(quán)角色和權(quán)限
*
* @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() {
// 權(quán)限控制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");
// 放行未授權(quán)接口,重定向使用
filterChainDefinitionMap.put("/api/auth/unauth", "anon");
// token過期接口
filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
// 被擠下線
filterChainDefinitionMap.put("/api/auth/downline", "anon");
// 放行 end ----------------------------------------------------------
// 從數(shù)據(jù)庫或緩存中查取出來的url與resources對應(yīng)則不會被攔截 放行
List<Menu> permissionList = menuMapper.selectList( null );
if ( !CollectionUtils.isEmpty( permissionList ) ) {
permissionList.forEach( e -> {
if ( StringUtils.isNotBlank( e.getUrl() ) ) {
// 根據(jù)url查詢相關(guān)聯(lián)的角色名,拼接自定義的角色權(quán)限
List<Role> roleList = roleMapper.selectRoleByMenuId( e.getId() );
StringJoiner zqRoles = new StringJoiner(",", "zqRoles[", "]");
if ( !CollectionUtils.isEmpty( roleList ) ){
roleList.forEach( f -> {
zqRoles.add( f.getCode() );
});
}
// 注意過濾器配置順序不能顛倒
// ① 認(rèn)證登錄
// ② 認(rèn)證自定義的token過濾器 - 判斷token是否有效
// ③ 角色權(quán)限 zqRoles:自定義的只需要滿足其中一個角色即可訪問 ; roles[admin,guest] : 默認(rèn)需要每個參數(shù)滿足才算通過,相當(dāng)于hasAllRoles()方法
// ④ zqPerms:認(rèn)證自定義的url過濾器攔截權(quán)限 【注:多個過濾器用 , 分割】
// 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]"); // 寫死的一種用法
}
});
}
// ⑤ 認(rèn)證登錄 【注: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:如果僅僅是更新的話,可以根據(jù)這里的 map 遍歷數(shù)據(jù)修改,重新整理好權(quán)限再一起添加
shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
// 動態(tài)查詢數(shù)據(jù)庫中所有權(quán)限
shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitionMap());
// 重新構(gòu)建生成攔截
Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
for (Map.Entry<String, String> entry : chains.entrySet()) {
manager.createChain(entry.getKey(), entry.getValue());
}
log.info("--------------- 動態(tài)生成url權(quán)限成功! ---------------");
// 動態(tài)更新該角色相關(guān)聯(lián)的用戶shiro權(quán)限
if(roleId != null){
updatePermissionByRoleId(roleId,isRemoveSession);
}
}
}
@Override
public void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession) {
// 查詢當(dāng)前角色的用戶shiro緩存信息 -> 實現(xiàn)動態(tài)權(quán)限
List<User> userList = userMapper.selectUserByRoleId(roleId);
// 刪除當(dāng)前角色關(guān)聯(lián)的用戶緩存信息,用戶再次訪問接口時會重新授權(quán) ; isRemoveSession為true時刪除Session -> 即強制用戶退出
if ( !CollectionUtils.isEmpty( userList ) ) {
for (User user : userList) {
ShiroUtils.deleteCache(user.getUsername(), isRemoveSession);
}
}
log.info("--------------- 動態(tài)修改用戶權(quán)限成功! ---------------");
}
}四、shiro中自定義角色與權(quán)限過濾器
1、自定義uri權(quán)限過濾器 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);
// 檢查是否擁有訪問權(quán)限
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
// 轉(zhuǎn)換成http的請求和響應(yīng)
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\":\"沒有權(quán)限操作!\"}");
}else { //正常請求
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}
}2、自定義角色權(quán)限過濾器 zqRoles
shiro原生的角色過濾器RolesAuthorizationFilter 默認(rèn)是必須同時滿足roles[admin,guest]才有權(quán)限,而自定義的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;
// 沒有角色限制,有權(quán)限訪問
if (rolesArray == null || rolesArray.length == 0) {
return true;
}
for (int i = 0; i < rolesArray.length; i++) {
//若當(dāng)前用戶是rolesArray中的任何一個,則有權(quán)限訪問
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";
/**
* 判斷是否擁有權(quán)限 true:認(rèn)證成功 false:認(rèn)證失敗
* mappedValue 訪問該url時需要的權(quán)限
* subject.isPermitted 判斷訪問的用戶是否擁有mappedValue權(quán)限
*/
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 根據(jù)請求頭拿到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;
}
/**
* 認(rèn)證失敗回調(diào)的方法: 如果登錄實體為null就保存請求和跳轉(zhuǎn)登錄頁面,否則就跳轉(zhuǎn)無權(quán)限配置頁面
*/
@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 {
/** 私有構(gòu)造器 **/
private ShiroUtils(){ }
private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);
/**
* 獲取當(dāng)前用戶Session
* @Return SysUserEntity 用戶信息
*/
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
/**
* 用戶登出
*/
public static void logout() {
SecurityUtils.getSubject().logout();
}
/**
* 獲取當(dāng)前用戶信息
* @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;
// 獲取當(dāng)前已登錄的用戶session列表
Collection<Session> sessions = redisSessionDAO.getActiveSessions();
User sysUserEntity;
Object attribute = null;
// 遍歷Session,找到該用戶名稱對應(yīng)的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,再訪問受限接口時會重新授權(quán)
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
Authenticator authc = securityManager.getAuthenticator();
((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
}
/**
* 從緩存中獲取指定用戶名的Session
* @param username
*/
private static Session getSessionByUsername(String username){
// 獲取當(dāng)前已登錄的用戶session列表
Collection<Session> sessions = redisSessionDAO.getActiveSessions();
User user;
Object attribute;
// 遍歷Session,找到該用戶名稱對應(yīng)的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作為參數(shù)傳入進去
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 通過Name返回指定的Bean
*/
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}六、案例demo源碼
到此這篇關(guān)于SpringBoot使用Shiro實現(xiàn)動態(tài)加載權(quán)限詳解流程的文章就介紹到這了,更多相關(guān)SpringBoot動態(tài)加載權(quán)限內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在idea中使用JaCoCo插件統(tǒng)計單元測試覆蓋率的實現(xiàn)
這篇文章主要介紹了在idea中使用JaCoCo插件統(tǒng)計單元測試覆蓋率的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
SpringBoot 項目中的圖片處理策略之本地存儲與路徑映射
在SpringBoot項目中,靜態(tài)資源存放在static目錄下,使得前端可以通過URL來訪問這些資源,我們就需要將文件系統(tǒng)的文件路徑與URL建立一個映射關(guān)系,把文件系統(tǒng)中的文件當(dāng)成我們的靜態(tài)資源即可,本文給大家介紹SpringBoot本地存儲與路徑映射的相關(guān)知識,感興趣的朋友一起看看吧2023-12-12
Java實現(xiàn)鏈表數(shù)據(jù)結(jié)構(gòu)的方法
這篇文章主要介紹了Java實現(xiàn)鏈表數(shù)據(jù)結(jié)構(gòu)的相關(guān)資料,每一個鏈表都包含多個節(jié)點,節(jié)點又包含兩個部分,一個是數(shù)據(jù)域(儲存節(jié)點含有的信息),一個是引用域(儲存下一個節(jié)點或者上一個節(jié)點的地址),需要的朋友可以參考下2022-01-01
Spring通過c3p0配置bean連接數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了Spring通過c3p0配置bean連接數(shù)據(jù)庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08

