一、前言
本文小編將基于 SpringBoot 集成 Shiro 實(shí)現(xiàn)動(dòng)態(tài)uri權(quán)限隧膏,由前端vue在頁(yè)面配置uri哗讥,Java后端動(dòng)態(tài)刷新權(quán)限,不用重啟項(xiàng)目私植,以及在頁(yè)面分配給用戶 角色 忌栅、 按鈕 、uri 權(quán)限后,后端動(dòng)態(tài)分配權(quán)限索绪,用戶無(wú)需在頁(yè)面重新登錄才能獲取最新權(quán)限湖员,一切權(quán)限動(dòng)態(tài)加載,靈活配置
基本環(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)限攔截驗(yà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)證 (主要是在登錄時(shí)的邏輯處理) -
doGetAuthorizationInfo
:登陸認(rèn)證成功后的處理 ex: 賦予角色和權(quán)限
【 注:用戶進(jìn)行權(quán)限驗(yàn)證時(shí) Shiro會(huì)去緩存中找,如果查不到數(shù)據(jù),會(huì)執(zhí)行doGetAuthorizationInfo這個(gè)方法去查權(quán)限,并放入緩存中 】
-> 因此我們?cè)谇岸隧?yè)面分配用戶權(quán)限時(shí) 執(zhí)行清除shiro緩存的方法即可實(shí)現(xiàn)動(dòng)態(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)限:用戶進(jìn)行權(quán)限驗(yàn)證時(shí) Shiro會(huì)去緩存中找,如果查不到數(shù)據(jù),會(huì)執(zhí)行這個(gè)方法去查權(quán)限,并放入緩存中
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 獲取用戶
User user = (User) principalCollection.getPrimaryPrincipal();
Integer userId =user.getId();
// 這里可以進(jìn)行授權(quán)和處理
Set<String> rolesSet = new HashSet<>();
Set<String> permsSet = new HashSet<>();
// 獲取當(dāng)前用戶對(duì)應(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;
// 獲取用戶輸入的賬號(hào)
String username = tokenInfo.getUsername();
// 獲取用戶輸入的密碼
String password = String.valueOf( tokenInfo.getPassword() );
// 通過(guò)username從數(shù)據(jù)庫(kù)中查找 User對(duì)象,如果找到進(jìn)行驗(yàn)證
// 實(shí)際項(xiàng)目中,這里可以根據(jù)實(shí)際情況做緩存,如果不做,Shiro自己也是有時(shí)間間隔機(jī)制,2分鐘內(nèi)不會(huì)重復(fù)執(zhí)行該方法
User user = userMapper.selectUserByUsername(username);
// 判斷賬號(hào)是否存在
if (user == null) {
//返回null -> shiro就會(huì)知道這是用戶不存在的異常
return null;
}
// 驗(yàn)證密碼 【注:這里不采用shiro自身密碼驗(yàn)證 彤侍, 采用的話會(huì)導(dǎo)致用戶登錄密碼錯(cuò)誤時(shí)肠缨,已登錄的賬號(hào)也會(huì)自動(dòng)下線! 如果采用盏阶,移除下面的清除緩存到登錄處 處理】
if ( !password.equals( user.getPwd() ) ){
throw new IncorrectCredentialsException("用戶名或者密碼錯(cuò)誤");
}
// 判斷賬號(hào)是否被凍結(jié)
if (user.getFlag()==null|| "0".equals(user.getFlag())){
throw new LockedAccountException();
}
/**
* 進(jìn)行驗(yàn)證 -> 注:shiro會(huì)自動(dòng)驗(yàn)證密碼
* 參數(shù)1:principal -> 放對(duì)象就可以在頁(yè)面任意地方拿到該對(duì)象里面的值
* 參數(shù)2:hashedCredentials -> 密碼
* 參數(shù)3:credentialsSalt -> 設(shè)置鹽值
* 參數(shù)4:realmName -> 自定義的Realm
*/
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
// 驗(yàn)證成功開(kāi)始踢人(清除緩存和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)過(guò)期時(shí)間30分鐘,即在30分鐘內(nèi)不進(jìn)行操作則清空緩存信息名斟,頁(yè)面即會(huì)提醒重新登錄
*/
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;
/**
* 開(kāi)啟Shiro-aop注解支持:使用代理方式所以需要開(kāi)啟代碼支持
*/
@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);
// 自定義過(guò)濾器
Map<String, Filter> filtersMap = new LinkedHashMap<>();
// 定義過(guò)濾器名稱 【注:map里面key值對(duì)于的value要為authc才能使用自定義的過(guò)濾器】
filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() );
filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() );
filtersMap.put( "token", new TokenCheckFilter() );
shiroFilterFactoryBean.setFilters(filtersMap);
// 登錄的路徑: 如果你沒(méi)有登錄則會(huì)跳到這個(gè)頁(yè)面中 - 如果沒(méi)有設(shè)置值則會(huì)默認(rèn)跳轉(zhuǎn)到工程根目錄下的"/login.jsp"頁(yè)面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
// 登錄成功后跳轉(zhuǎn)的主頁(yè)面 (這里沒(méi)用脑慧,前端vue控制了跳轉(zhuǎn))
// shiroFilterFactoryBean.setSuccessUrl("/index");
// 設(shè)置沒(méi)有權(quán)限時(shí)跳轉(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實(shí)現(xiàn)緩存管理
securityManager.setCacheManager(cacheManager());
// 自定義Realm驗(yàn)證
securityManager.setRealm(shiroRealm());
return securityManager;
}
/**
* 身份驗(yàn)證器
*/
@Bean
public ShiroRealm shiroRealm() {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
/**
* 自定義Realm的加密規(guī)則 -> 憑證匹配器:將密碼校驗(yàn)交給Shiro的SimpleAuthenticationInfo進(jìn)行處理,在這里做匹配配置
*/
@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開(kāi)源插件
*/
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
return redisManager;
}
/**
* 配置Cache管理器:用于往Redis存儲(chǔ)權(quán)限和角色標(biāo)識(shí) (使用的是shiro-redis開(kāi)源插件)
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
redisCacheManager.setKeyPrefix(CACHE_KEY);
// 配置緩存的話要求放在session里面的實(shí)體類必須有個(gè)id標(biāo)識(shí) 注:這里id為用戶表中的主鍵闷袒,否-> 報(bào):User must has getter for field: xx
redisCacheManager.setPrincipalIdFieldName("id");
return redisCacheManager;
}
/**
* SessionID生成器
*/
@Bean
public ShiroSessionIdGenerator sessionIdGenerator(){
return new ShiroSessionIdGenerator();
}
/**
* 配置RedisSessionDAO (使用的是shiro-redis開(kāi)源插件)
*/
@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動(dòng)態(tài)加載權(quán)限處理方法
-
loadFilterChainDefinitionMap
:初始化權(quán)限
ex: 在上面Shiro配置類ShiroConfig
中的Shiro基礎(chǔ)配置shiroFilterFactory
方法中我們就需要調(diào)用此方法將數(shù)據(jù)庫(kù)中配置的所有uri權(quán)限全部加載進(jìn)去岩梳,以及放行接口和配置權(quán)限過(guò)濾器等
【注:過(guò)濾器配置順序不能顛倒囊骤,多個(gè)過(guò)濾器用
,分割】
ex:filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
-
updatePermission
:動(dòng)態(tài)刷新加載數(shù)據(jù)庫(kù)中的uri權(quán)限 -> 頁(yè)面在新增uri路徑到數(shù)據(jù)庫(kù)中,也就是配置新的權(quán)限時(shí)就可以調(diào)用此方法實(shí)現(xiàn)動(dòng)態(tài)加載uri權(quán)限 -
updatePermissionByRoleId
:shiro動(dòng)態(tài)權(quán)限加載 -> 即分配指定用戶權(quán)限時(shí)可調(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();
/**
* 在對(duì)uri權(quán)限進(jìn)行增刪改操作時(shí)淘捡,需要調(diào)用此方法進(jìn)行動(dòng)態(tài)刷新加載數(shù)據(jù)庫(kù)中的uri權(quán)限
*
* @param shiroFilterFactoryBean
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
/**
* shiro動(dòng)態(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<>();
// 配置過(guò)濾:不會(huì)被攔截的鏈接 -> 放行 start ----------------------------------------------------------
// 放行Swagger2頁(yè)面池摧,需要放行這些
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過(guò)期接口
filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
// 被擠下線
filterChainDefinitionMap.put("/api/auth/downline", "anon");
// 放行 end ----------------------------------------------------------
// 從數(shù)據(jù)庫(kù)或緩存中查取出來(lái)的url與resources對(duì)應(yīng)則不會(huì)被攔截 放行
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() );
});
}
// 注意過(guò)濾器配置順序不能顛倒
// ① 認(rèn)證登錄
// ② 認(rèn)證自定義的token過(guò)濾器 - 判斷token是否有效
// ③ 角色權(quán)限 zqRoles:自定義的只需要滿足其中一個(gè)角色即可訪問(wèn) ; roles[admin,guest] : 默認(rèn)需要每個(gè)參數(shù)滿足才算通過(guò),相當(dāng)于hasAllRoles()方法
// ④ zqPerms:認(rèn)證自定義的url過(guò)濾器攔截權(quán)限 【注:多個(gè)過(guò)濾器用 , 分割】
// 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();
// 清空攔截管理器中的存儲(chǔ)
manager.getFilterChains().clear();
// 清空攔截工廠中的存儲(chǔ),如果不清空這里,還會(huì)把之前的帶進(jìn)去
// ps:如果僅僅是更新的話,可以根據(jù)這里的 map 遍歷數(shù)據(jù)修改,重新整理好權(quán)限再一起添加
shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
// 動(dòng)態(tài)查詢數(shù)據(jù)庫(kù)中所有權(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("--------------- 動(dòng)態(tài)生成url權(quán)限成功作彤! ---------------");
// 動(dòng)態(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緩存信息 -> 實(shí)現(xiàn)動(dòng)態(tài)權(quán)限
List<User> userList = userMapper.selectUserByRoleId(roleId);
// 刪除當(dāng)前角色關(guān)聯(lián)的用戶緩存信息,用戶再次訪問(wèn)接口時(shí)會(huì)重新授權(quán) ; isRemoveSession為true時(shí)刪除Session -> 即強(qiáng)制用戶退出
if ( !CollectionUtils.isEmpty( userList ) ) {
for (User user : userList) {
ShiroUtils.deleteCache(user.getUsername(), isRemoveSession);
}
}
log.info("--------------- 動(dòng)態(tài)修改用戶權(quán)限成功膘魄! ---------------");
}
}
四、shiro中自定義角色竭讳、權(quán)限過(guò)濾器
1创葡、自定義uri權(quán)限過(guò)濾器 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("請(qǐng)求的url: " + requestUrl);
// 檢查是否擁有訪問(wèn)權(quán)限
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
// 轉(zhuǎn)換成http的請(qǐng)求和響應(yīng)
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 獲取請(qǐng)求頭的值
String header = req.getHeader("X-Requested-With");
// ajax 的請(qǐng)求頭里有X-Requested-With: XMLHttpRequest 正常請(qǐng)求沒(méi)有
if (header!=null && "XMLHttpRequest".equals(header)){
resp.setContentType("text/json,charset=UTF-8");
resp.getWriter().print("{\"success\":false,\"msg\":\"沒(méi)有權(quán)限操作!\"}");
}else { //正常請(qǐng)求
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}
}
2绢慢、自定義角色權(quán)限過(guò)濾器 zqRoles
shiro原生的角色過(guò)濾器RolesAuthorizationFilter 默認(rèn)是必須同時(shí)滿足roles[admin,guest]
才有權(quán)限灿渴,而自定義的zqRoles
只滿足其中一個(gè)即可訪問(wèn)
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;
// 沒(méi)有角色限制,有權(quán)限訪問(wèn)
if (rolesArray == null || rolesArray.length == 0) {
return true;
}
for (int i = 0; i < rolesArray.length; i++) {
//若當(dāng)前用戶是rolesArray中的任何一個(gè),則有權(quán)限訪問(wèn)
if (subject.hasRole(rolesArray[i])) {
return true;
}
}
return false;
}
}
3骚露、自定義token過(guò)濾器 token
-> 判斷token是否過(guò)期失效等
@Slf4j
public class TokenCheckFilter extends UserFilter {
/**
* token過(guò)期蹬挤、失效
*/
private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";
/**
* 判斷是否擁有權(quán)限 true:認(rèn)證成功 false:認(rèn)證失敗
* mappedValue 訪問(wèn)該url時(shí)需要的權(quán)限
* subject.isPermitted 判斷訪問(wèn)的用戶是否擁有mappedValue權(quán)限
*/
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 根據(jù)請(qǐng)求頭拿到token
String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);
log.info("瀏覽器token:" + token );
User userInfo = ShiroUtils.getUserInfo();
String userToken = userInfo.getToken();
// 檢查token是否過(guò)期
if ( !token.equals(userToken) ){
return false;
}
return true;
}
/**
* 認(rèn)證失敗回調(diào)的方法: 如果登錄實(shí)體為null就保存請(qǐng)求和跳轉(zhuǎn)登錄頁(yè)面,否則就跳轉(zhuǎn)無(wú)權(quán)限配置頁(yè)面
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
User userInfo = ShiroUtils.getUserInfo();
// 重定向錯(cuò)誤提示處理 - 前后端分離情況下
WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
return false;
}
}
五、項(xiàng)目中會(huì)用到的一些工具類棘幸、常量等
溫馨小提示:這里只是部分焰扳,詳情可參考文章末尾給出的案例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,找到該用戶名稱對(duì)應(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;
// 清除該用戶以前登錄時(shí)保存的session吨悍,強(qiáng)制退出 -> 單用戶登錄處理
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
}
}
if (session == null||attribute == null) {
return;
}
//刪除session
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
//刪除Cache,再訪問(wèn)受限接口時(shí)會(huì)重新授權(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,找到該用戶名稱對(duì)應(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初始化后會(huì)判斷是不是ApplicationContextAware的子類
* 如果該類是,setApplicationContext()方法,會(huì)將容器中ApplicationContext作為參數(shù)傳入進(jìn)去
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 通過(guò)Name返回指定的Bean
*/
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}