色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術(shù)文章
文章詳情頁

關(guān)于Spring Boot動(dòng)態(tài)權(quán)限變更問題的實(shí)現(xiàn)方案

瀏覽:4日期:2023-07-05 09:24:02
1、前言

​  在Web項(xiàng)目中,權(quán)限管理即權(quán)限訪問控制為網(wǎng)站訪問安全提供了保障,并且很多項(xiàng)目使用了Session作為緩存,結(jié)合AOP技術(shù)進(jìn)行token認(rèn)證和權(quán)限控制。權(quán)限控制流程大致如下圖所示:

關(guān)于Spring Boot動(dòng)態(tài)權(quán)限變更問題的實(shí)現(xiàn)方案

​  現(xiàn)在,如果管理員修改了用戶的角色,或修改了角色的權(quán)限,都會(huì)導(dǎo)致用戶權(quán)限發(fā)生變化,此時(shí)如何實(shí)現(xiàn)動(dòng)態(tài)權(quán)限變更,使得前端能夠更新用戶的權(quán)限樹,后端訪問鑒權(quán)AOP模塊能夠知悉這種變更呢?

2、問題及解決方案

​​  現(xiàn)在的問題是,管理員沒法訪問用戶Session,因此沒法將變更通知此用戶。而用戶如果已經(jīng)登錄,或直接關(guān)閉瀏覽器頁面而不是登出操作,Session沒有過期前,用戶訪問接口時(shí),訪問鑒權(quán)AOP模塊仍然是根據(jù)之前緩存的Session信息進(jìn)行處理,沒法做到動(dòng)態(tài)權(quán)限變更。

​​  使用Security+WebSocket是一個(gè)方案,但沒法處理不在線用戶。

​​  ​解決方案的核心思想是利用ServletContext對(duì)象的共享特性,來實(shí)現(xiàn)用戶權(quán)限變更的信息傳遞。然后在AOP類中查詢用戶是否有變更通知記錄需要處理,如果權(quán)限發(fā)生變化,則修改response消息體,添加附加通知信息給前端。前端收到附加的通知信息,可更新功能權(quán)限樹,并進(jìn)行相關(guān)處理。

​​​  這樣,利用的變更通知服務(wù),不僅后端的用戶url訪問接口可第一時(shí)間獲悉變更,還可以通知到前端,從而實(shí)現(xiàn)了動(dòng)態(tài)權(quán)限變更。

3、方案實(shí)現(xiàn)3.1、開發(fā)變更通知類

​​​  服務(wù)接口類ChangeNotifyService,代碼如下:

package com.abc.questInvest.service;/** * @className: ChangeNotifyService * @description: 變更通知服務(wù) * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */public interface ChangeNotifyService {/** * * @methodName: getChangeNotifyInfo * @description: 獲取指定用戶ID的變更通知信息 * @param userId: 用戶ID * @return: 返回0表示無變更通知信息,其它值按照bitmap編碼。目前定義如下: * bit0:: 修改用戶的角色組合值,從而導(dǎo)致權(quán)限變更; * bit1:: 修改角色的功能項(xiàng),從而導(dǎo)致權(quán)限變更; * bit2:: 用戶禁用,從而導(dǎo)致權(quán)限變更; * bit3:: 用戶調(diào)整部門,從而導(dǎo)致數(shù)據(jù)權(quán)限變更; * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */public Integer getChangeNotifyInfo(Integer userId);/** * * @methodName: setChangeNotifyInfo * @description: 設(shè)置變更通知信息 * @param userId: 用戶ID * @param changeNotifyInfo: 變更通知值 * bit0:: 修改用戶的角色組合值,從而導(dǎo)致權(quán)限變更; * bit1:: 修改角色的功能項(xiàng),從而導(dǎo)致權(quán)限變更; * bit2:: 用戶禁用,從而導(dǎo)致權(quán)限變更; * bit3:: 用戶調(diào)整部門,從而導(dǎo)致數(shù)據(jù)權(quán)限變更; * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */public void setChangeNotifyInfo(Integer userId,Integer changeNotifyInfo); }

​​​  服務(wù)實(shí)現(xiàn)類ChangeNotifyServiceImpl,代碼如下:

package com.abc.questInvest.service.impl;import java.util.HashMap;import java.util.Map;import org.springframework.stereotype.Service;import com.abc.questInvest.service.ChangeNotifyService;/** * @className: ChangeNotifyServiceImpl * @description: ChangeNotifyService實(shí)現(xiàn)類 * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */@Servicepublic class ChangeNotifyServiceImpl implements ChangeNotifyService {//用戶ID與變更過通知信息映射表private Map<Integer,Integer> changeNotifyMap = new HashMap<Integer,Integer>();/** * * @methodName: getChangeNotifyInfo * @description: 獲取指定用戶ID的變更通知信息 * @param userId: 用戶ID * @return: 返回0表示無變更通知信息,其它值按照bitmap編碼。目前定義如下: * bit0:: 修改用戶的角色組合值,從而導(dǎo)致權(quán)限變更; * bit1:: 修改角色的功能項(xiàng),從而導(dǎo)致權(quán)限變更; * bit2:: 用戶禁用,從而導(dǎo)致權(quán)限變更; * bit3:: 用戶調(diào)整部門,從而導(dǎo)致數(shù)據(jù)權(quán)限變更; * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */@Overridepublic Integer getChangeNotifyInfo(Integer userId) {Integer changeNotifyInfo = 0;//檢查該用戶是否有變更通知信息if (changeNotifyMap.containsKey(userId)) {changeNotifyInfo = changeNotifyMap.get(userId);//移除數(shù)據(jù),加鎖保護(hù)synchronized(changeNotifyMap) {changeNotifyMap.remove(userId);}}return changeNotifyInfo;}/** * * @methodName: setChangeNotifyInfo * @description: 設(shè)置變更通知信息,該功能一般由管理員觸發(fā)調(diào)用 * @param userId: 用戶ID * @param changeNotifyInfo: 變更通知值 * bit0:: 修改用戶的角色組合值,從而導(dǎo)致權(quán)限變更; * bit1:: 修改角色的功能項(xiàng),從而導(dǎo)致權(quán)限變更; * bit2:: 用戶禁用,從而導(dǎo)致權(quán)限變更; * bit3:: 用戶調(diào)整部門,從而導(dǎo)致數(shù)據(jù)權(quán)限變更; * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */@Overridepublic void setChangeNotifyInfo(Integer userId,Integer changeNotifyInfo) {//檢查該用戶是否有變更通知信息if (changeNotifyMap.containsKey(userId)) {//如果有,表示之前變更通知未處理//獲取之前的值Integer oldChangeNotifyInfo = changeNotifyMap.get(userId);//計(jì)算新值。bitmap編碼,或操作Integer newChangeNotifyInfo = oldChangeNotifyInfo | changeNotifyInfo;//設(shè)置數(shù)據(jù),加鎖保護(hù)synchronized(changeNotifyMap) {changeNotifyMap.put(userId,newChangeNotifyInfo);}}else {//如果沒有,設(shè)置一條changeNotifyMap.put(userId,changeNotifyInfo);}}}

​​  此處,變更通知類型,與使用的demo項(xiàng)目有關(guān),目前定義了4種變更通知類型。實(shí)際上,除了權(quán)限相關(guān)的變更,還有與Session緩存字段相關(guān)的變更,也需要通知,否則用戶還是在使用舊數(shù)據(jù)。

3.2、將變更通知類對(duì)象,納入全局配置服務(wù)對(duì)象中進(jìn)行管理

​​​  全局配置服務(wù)類GlobalConfigService,負(fù)責(zé)管理全局的配置服務(wù)對(duì)象,服務(wù)接口類代碼如下:

package com.abc.questInvest.service;/** * @className: GlobalConfigService * @description: 全局變量管理類 * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/021.0.0sheng.zheng初版 * */public interface GlobalConfigService {/** * * @methodName: loadData * @description: 加載數(shù)據(jù) * @return: 成功返回true,否則返回false * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/021.0.0sheng.zheng初版 * */public boolean loadData();//獲取TableCodeConfigService對(duì)象public TableCodeConfigService getTableCodeConfigService();//獲取SysParameterService對(duì)象public SysParameterService getSysParameterService();//獲取FunctionTreeService對(duì)象public FunctionTreeService getFunctionTreeService();//獲取RoleFuncRightsService對(duì)象public RoleFuncRightsService getRoleFuncRightsService();//獲取ChangeNotifyService對(duì)象public ChangeNotifyService getChangeNotifyService();}

​​​  服務(wù)實(shí)現(xiàn)類GlobalConfigServiceImpl,代碼如下:

package com.abc.questInvest.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.abc.questInvest.service.ChangeNotifyService;import com.abc.questInvest.service.FunctionTreeService;import com.abc.questInvest.service.GlobalConfigService;import com.abc.questInvest.service.RoleFuncRightsService;import com.abc.questInvest.service.SysParameterService;import com.abc.questInvest.service.TableCodeConfigService;/** * @className: GlobalConfigServiceImpl * @description: GlobalConfigService實(shí)現(xiàn)類 * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/021.0.0sheng.zheng初版 * */@Servicepublic class GlobalConfigServiceImpl implements GlobalConfigService{//ID編碼配置表數(shù)據(jù)服務(wù)@Autowiredprivate TableCodeConfigService tableCodeConfigService;//系統(tǒng)參數(shù)表數(shù)據(jù)服務(wù)@Autowiredprivate SysParameterService sysParameterService;//功能樹表數(shù)據(jù)服務(wù)@Autowiredprivate FunctionTreeService functionTreeService;//角色權(quán)限表數(shù)據(jù)服務(wù)@Autowiredprivate RoleFuncRightsService roleFuncRightsService;//變更通知服務(wù)@Autowiredprivate ChangeNotifyService changeNotifyService;/** * * @methodName: loadData * @description: 加載數(shù)據(jù) * @return: 成功返回true,否則返回false * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/021.0.0sheng.zheng初版 * */@Overridepublic boolean loadData() {boolean bRet = false;//加載table_code_config表記錄bRet = tableCodeConfigService.loadData();if (!bRet) {return bRet;}//加載sys_parameters表記錄bRet = sysParameterService.loadData();if (!bRet) {return bRet;}//changeNotifyService目前沒有持久層,無需加載//如果服務(wù)重啟,信息丟失,也沒關(guān)系,因?yàn)榇藭r(shí)Session也會(huì)失效//加載function_tree表記錄bRet = functionTreeService.loadData();if (!bRet) {return bRet;}//加載role_func_rights表記錄//先設(shè)置完整功能樹roleFuncRightsService.setFunctionTree(functionTreeService.getFunctionTree());//然后加載數(shù)據(jù)bRet = roleFuncRightsService.loadData();if (!bRet) {return bRet;}return bRet;}//獲取TableCodeConfigService對(duì)象@Overridepublic TableCodeConfigService getTableCodeConfigService() {return tableCodeConfigService;}//獲取SysParameterService對(duì)象@Overridepublic SysParameterService getSysParameterService() {return sysParameterService;}//獲取FunctionTreeService對(duì)象@Overridepublic FunctionTreeService getFunctionTreeService() {return functionTreeService;}//獲取RoleFuncRightsService對(duì)象@Overridepublic RoleFuncRightsService getRoleFuncRightsService() {return roleFuncRightsService;}//獲取ChangeNotifyService對(duì)象@Overridepublic ChangeNotifyService getChangeNotifyService() {return changeNotifyService;}}

​​  GlobalConfigServiceImpl類,管理了很多配置服務(wù)類,此處主要關(guān)注ChangeNotifyService類對(duì)象。

3.3、使用ServletContext,管理全局配置服務(wù)類對(duì)象

​​​  全局配置服務(wù)類在應(yīng)用啟動(dòng)時(shí)加載到Spring容器中,這樣可實(shí)現(xiàn)共享,減少對(duì)數(shù)據(jù)庫的訪問壓力。

​​​  實(shí)現(xiàn)一個(gè)ApplicationListener類,代碼如下:

package com.abc.questInvest;import javax.servlet.ServletContext;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;import org.springframework.web.context.WebApplicationContext;import com.abc.questInvest.service.GlobalConfigService;/** * @className: ApplicationStartup * @description: 應(yīng)用偵聽器 * */@Componentpublic class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent>{ //全局變量管理對(duì)象,此處不能自動(dòng)注入 private GlobalConfigService globalConfigService = null;@Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {try {if(contextRefreshedEvent.getApplicationContext().getParent() == null){ //root application context 沒有parent.System.out.println('========定義全局變量==================');// 將 ApplicationContext 轉(zhuǎn)化為 WebApplicationContext WebApplicationContext webApplicationContext = (WebApplicationContext)contextRefreshedEvent.getApplicationContext(); // 從 webApplicationContext 中獲取 servletContext ServletContext servletContext = webApplicationContext.getServletContext();//加載全局變量管理對(duì)象 globalConfigService = (GlobalConfigService)webApplicationContext.getBean(GlobalConfigService.class); //加載數(shù)據(jù) boolean bRet = globalConfigService.loadData(); if (false == bRet) { System.out.println('加載全局變量失敗'); return; } //====================================================================== // servletContext設(shè)置值 servletContext.setAttribute('GLOBAL_CONFIG_SERVICE', globalConfigService); } } catch (Exception e) {e.printStackTrace(); } }}

​​​  在啟動(dòng)類中,加入該應(yīng)用偵聽器ApplicationStartup。

public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(QuestInvestApplication.class);springApplication.addListeners(new ApplicationStartup());springApplication.run(args); }

​​  現(xiàn)在,有了一個(gè)GlobalConfigService類型的全局變量globalConfigService。

3.4、發(fā)出變更通知

​​​  此處舉2個(gè)例子,說明發(fā)出變更通知的例子,這兩個(gè)例子,都在用戶管理模塊,UserManServiceImpl類中。

​​​  1)管理員修改用戶信息,可能導(dǎo)致權(quán)限相關(guān)項(xiàng)發(fā)生變動(dòng),2)禁用用戶,發(fā)出變更過通知。

​​​  發(fā)出通知的相關(guān)代碼如下:

/** * * @methodName: editUser * @description: 修改用戶信息 * @param userInfo: 用戶信息對(duì)象 * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/081.0.0sheng.zheng初版 * 2021/06/281.0.1sheng.zheng增加變更通知的處理 * */@Overridepublic void editUser(HttpServletRequest request,UserInfo userInfo) {//輸入?yún)?shù)校驗(yàn)checkValidForParams('editUser',userInfo);//獲取操作人賬號(hào)String operatorName = (String) request.getSession().getAttribute('username');userInfo.setOperatorName(operatorName);//登錄名和密碼不修改userInfo.setLoginName(null);userInfo.setSalt(null);userInfo.setPasswd(null);//獲取修改之前的用戶信息Integer userId = userInfo.getUserId();UserInfo oldUserInfo = userManDao.selectUserByKey(userId);//修改用戶記錄try {userManDao.updateSelective(userInfo);}catch(Exception e) {e.printStackTrace();log.error(e.getMessage());throw new BaseException(ExceptionCodes.USERS_EDIT_USER_FAILED);}//檢查是否有需要通知的變更Integer changeFlag = 0;if (userInfo.getRoles() != null) {if(oldUserInfo.getRoles() != userInfo.getRoles()) {//角色組合有變化,bit0changeFlag |= 0x01;}}if (userInfo.getDeptId() != null) {if (oldUserInfo.getDeptId() != userInfo.getDeptId()) {//部門ID有變化,bit3changeFlag |= 0x08;}}if (changeFlag > 0) {//如果有變更過通知項(xiàng)//獲取全局變量ServletContext servletContext = request.getServletContext();GlobalConfigService globalConfigService = (GlobalConfigService)servletContext.getAttribute('GLOBAL_CONFIG_SERVICE');globalConfigService.getChangeNotifyService().setChangeNotifyInfo(userId, changeFlag);}}/** * * @methodName: disableUser * @description: 禁用用戶 * @param params: map對(duì)象,形式如下: * { * 'userId': 1 * } * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/081.0.0sheng.zheng初版 * 2021/06/281.0.1sheng.zheng增加變更通知的處理 * */@Overridepublic void disableUser(HttpServletRequest request,Map<String,Object> params) {//輸入?yún)?shù)校驗(yàn)checkValidForParams('disableUser',params);UserInfo userInfo = new UserInfo();//獲取操作人賬號(hào)String operatorName = (String) request.getSession().getAttribute('username');//設(shè)置userInfo信息Integer userId = (Integer)params.get('userId');userInfo.setUserId(userId);userInfo.setOperatorName(operatorName);//設(shè)置禁用標(biāo)記userInfo.setDeleteFlag((byte)1);//修改密碼try {userManDao.updateEnable(userInfo);}catch(Exception e) {e.printStackTrace();log.error(e.getMessage());throw new BaseException(ExceptionCodes.USERS_EDIT_USER_FAILED);}//禁用用戶,發(fā)出變更通知//獲取全局變量ServletContext servletContext = request.getServletContext();GlobalConfigService globalConfigService = (GlobalConfigService)servletContext.getAttribute('GLOBAL_CONFIG_SERVICE');//禁用用戶:bit2globalConfigService.getChangeNotifyService().setChangeNotifyInfo(userId, 0x04);}

​​  本demo項(xiàng)目的角色相對(duì)較少,沒有使用用戶角色關(guān)系表,而是使用了bitmap編碼,角色I(xiàn)D取值為2^n,用戶角色組合roles字段為一個(gè)Integer值。如roles=7,表示角色I(xiàn)D組合=[1,2,4]。​​  另外,如果修改了角色的功能權(quán)限集合,則需要查詢受影響的用戶ID列表,依次發(fā)出通知,可類似處理。

3.5、修改Response響應(yīng)消息體

​​​  Response響應(yīng)消息體,為BaseResponse,代碼如下:

package com.abc.questInvest.vo.common;import lombok.Data;/** * @className: BaseResponse * @description: 基本響應(yīng)消息體對(duì)象 * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/05/311.0.0sheng.zheng初版 * 2021/06/281.0.1sheng.zheng增加變更通知的附加信息 * */@Datapublic class BaseResponse<T> { //響應(yīng)碼 private int code; //響應(yīng)消息 private String message; //響應(yīng)實(shí)體信息 private T data; //分頁信息 private Page page; //附加通知信息 private Additional additional;}

​​  BaseResponse類增加了Additional類型的additional屬性字段,用于輸出附加信息。

​​  Additional類的定義如下:

package com.abc.questInvest.vo.common;import lombok.Data;/** * @className: Additional * @description: 附加信息 * @summary: * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/281.0.0sheng.zheng初版 * */@Datapublic class Additional { //通知碼,附加信息 private int notifycode; //通知碼對(duì)應(yīng)的消息 private String notification;//更新的token private String token;//更新的功能權(quán)限樹 private String rights;}

​​  附加信息類Additional中,各屬性字段的說明:

notifycode,為通知碼,即可對(duì)應(yīng)通知消息的類型,目前只有一種,可擴(kuò)展。 notification,為通知碼對(duì)應(yīng)的消息。

​​  通知碼,在ExceptionCodes枚舉文件中定義:

//變更通知信息 USER_RIGHTS_CHANGED(51, 'message.USER_RIGHTS_CHANGED', '用戶權(quán)限發(fā)生變更'),; //end enum ExceptionCodes(int code, String messageId, String message) {this.code = code;this.messageId = messageId;this.message = message; } token,用于要求前端更新token。更新token的目的是確認(rèn)前端已經(jīng)收到權(quán)限變更通知。因?yàn)橄麓蝩rl請(qǐng)求將使用新的token,如果前端未收到或未處理,仍然用舊的token訪問,就要跳到登錄頁了。 rights,功能樹的字符串輸出,是樹型結(jié)構(gòu)的JSON字符串。

3.6、AOP鑒權(quán)處理

​​​  AuthorizationAspect為鑒權(quán)認(rèn)證的切面類,代碼如下:

package com.abc.questInvest.aop;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import com.abc.questInvest.common.constants.Constants;import com.abc.questInvest.common.utils.Utility;import com.abc.questInvest.dao.UserManDao;import com.abc.questInvest.entity.FunctionInfo;import com.abc.questInvest.entity.UserInfo;import com.abc.questInvest.exception.BaseException;import com.abc.questInvest.exception.ExceptionCodes;import com.abc.questInvest.service.GlobalConfigService;import com.abc.questInvest.service.LoginService;import com.abc.questInvest.vo.TreeNode;import com.abc.questInvest.vo.common.Additional;import com.abc.questInvest.vo.common.BaseResponse;/** * @className: AuthorizationAspect * @description: 接口訪問鑒權(quán)切面類 * @summary: 使用AOP,進(jìn)行token認(rèn)證以及用戶對(duì)接口的訪問權(quán)限鑒權(quán) * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks * ------------------------------------------------------------------------------ * 2021/06/061.0.0sheng.zheng初版 * 2021/06/281.0.1sheng.zheng增加變更通知的處理,增加了afterReturning增強(qiáng) * */@Aspect@Component@Order(2)public class AuthorizationAspect {@Autowired private UserManDao userManDao;//設(shè)置切點(diǎn) @Pointcut('execution(public * com.abc.questInvest.controller..*.*(..))' + '&& !execution(public * com.abc.questInvest.controller.LoginController.*(..))' + '&& !execution(public * com.abc.questInvest.controller.QuestInvestController.*(..))')public void verify(){}@Before('verify()') public void doVerify(){ ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request=attributes.getRequest(); // ================================================================================// token認(rèn)證//從header中獲取token值String token = request.getHeader('Authorization');if (null == token || token.equals('')){ //return;throw new BaseException(ExceptionCodes.TOKEN_IS_NULL); } //從session中獲取token和過期時(shí)間String sessionToken = (String)request.getSession().getAttribute('token');//判斷session中是否有信息,可能是非登錄用戶if (null == sessionToken || sessionToken.equals('')) {throw new BaseException(ExceptionCodes.TOKEN_WRONG);} //比較tokenif(!token.equals(sessionToken)) {//如果請(qǐng)求頭中的token與存在session中token兩者不一致throw new BaseException(ExceptionCodes.TOKEN_WRONG);}long expireTime = (long)request.getSession().getAttribute('expireTime');//檢查過期時(shí)間long time = System.currentTimeMillis();if (time > expireTime) {//如果token過期throw new BaseException(ExceptionCodes.TOKEN_EXPIRED);}else {//token未過期,更新過期時(shí)間long newExpiredTime = time + Constants.TOKEN_EXPIRE_TIME * 1000;request.getSession().setAttribute('expireTime', newExpiredTime);}// ============================================================================// 接口調(diào)用權(quán)限//獲取用戶IDInteger userId = (Integer)request.getSession().getAttribute('userId'); //獲取全局變量ServletContext servletContext = request.getServletContext();GlobalConfigService globalConfigService = (GlobalConfigService)servletContext.getAttribute('GLOBAL_CONFIG_SERVICE');//===================變更通知處理開始==============================================//檢查有無變更通知信息Integer changeNotifyInfo = globalConfigService.getChangeNotifyService().getChangeNotifyInfo(userId);//通知前端權(quán)限變更的標(biāo)記boolean rightsChangedFlag = false;if (changeNotifyInfo > 0) {//有通知信息if ((changeNotifyInfo & 0x09) > 0) {//bit0:修改用戶的角色組合值,從而導(dǎo)致權(quán)限變更//bit3:用戶調(diào)整部門,從而導(dǎo)致數(shù)據(jù)權(quán)限變更//mask 0b1001 = 0x09 //都需要查詢用戶表,并更新信息;合在一起查詢。UserInfo userInfo = userManDao.selectUserByKey(userId);//更新Session request.getSession().setAttribute('roles', userInfo.getRoles()); request.getSession().setAttribute('deptId', userInfo.getDeptId()); if ((changeNotifyInfo & 0x01) > 0) { //權(quán)限變更標(biāo)志置位 rightsChangedFlag = true; }}else if((changeNotifyInfo & 0x02) > 0) {//bit1:修改角色的功能值,從而導(dǎo)致權(quán)限變更 //權(quán)限變更標(biāo)志置位 rightsChangedFlag = true;}else if((changeNotifyInfo & 0x04) > 0) {//bit2:用戶禁用,從而導(dǎo)致權(quán)限變更//設(shè)置無效token,可阻止該用戶訪問系統(tǒng)request.getSession().setAttribute('token', '');//直接拋出異常,由前端顯示:Forbidden頁面throw new BaseException(ExceptionCodes.ACCESS_FORBIDDEN);}if (rightsChangedFlag == true) {//寫Session,用于將信息傳遞到afterReturning方法中request.getSession().setAttribute('rightsChanged', 1);}}//===================變更通知處理結(jié)束==============================================//從session中獲取用戶權(quán)限值Integer roles = (Integer)request.getSession().getAttribute('roles');//獲取當(dāng)前接口url值String servletPath = request.getServletPath();//獲取該角色對(duì)url的訪問權(quán)限Integer rights = globalConfigService.getRoleFuncRightsService().getRoleUrlRights(Utility.parseRoles(roles), servletPath);if (rights == 0) {//如果無權(quán)限訪問此接口,拋出異常,由前端顯示:Forbidden頁面throw new BaseException(ExceptionCodes.ACCESS_FORBIDDEN);} } @AfterReturning(value='verify()' ,returning='result') public void afterReturning(BaseResponse result) { //限制必須是BaseResponse類型,其它類型的返回值忽略 //獲取SessionServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();HttpServletRequest request = sra.getRequest(); Integer rightsChanged = (Integer)request.getSession().getAttribute('rightsChanged'); if (rightsChanged != null && rightsChanged == 1) { //如果有用戶權(quán)限變更,通知前端來刷新該用戶的功能權(quán)限樹 //構(gòu)造附加信息 Additional additional = new Additional(); additional.setNotifycode(ExceptionCodes.USER_RIGHTS_CHANGED.getCode()); additional.setNotification(ExceptionCodes.USER_RIGHTS_CHANGED.getMessage()); //更新token String loginName = (String)request.getSession().getAttribute('username'); String token = LoginService.generateToken(loginName); additional.setToken(token); //更新token,要求下次url訪問使用新的token request.getSession().setAttribute('token', token); //獲取用戶的功能權(quán)限樹 Integer roles = (Integer)request.getSession().getAttribute('roles'); ServletContext servletContext = request.getServletContext(); GlobalConfigService globalConfigService = (GlobalConfigService)servletContext.getAttribute('GLOBAL_CONFIG_SERVICE');//獲取用戶權(quán)限的角色功能樹 List<Integer> roleList = Utility.parseRoles(roles);TreeNode<FunctionInfo> rolesFunctionTree = globalConfigService.getRoleFuncRightsService().getRoleRights(roleList);additional.setRights(rolesFunctionTree.toString()); //修改response信息result.setAdditional(additional); //移除Session的rightsChanged項(xiàng) request.getSession().removeAttribute('rightsChanged'); } }}

​​  AuthorizationAspect類定義了切點(diǎn)verify(),@Before增強(qiáng)用于鑒權(quán)驗(yàn)證,增加了對(duì)變更通知信息的處理。并利用Session,用rightsChanged屬性字段記錄需要通知前端的標(biāo)志,在@AfterReturning后置增強(qiáng)中根據(jù)該屬性字段的值,進(jìn)行一步的處理。

​​  @Before增強(qiáng)的doVerify方法中,如果發(fā)現(xiàn)角色組合有改變,但仍有訪問此url權(quán)限時(shí),會(huì)繼續(xù)后續(xù)處理,這樣不會(huì)中斷業(yè)務(wù);如果沒有訪問此url權(quán)限,則返回訪問受限異常信息,由前端顯示訪問受限頁碼(類似403 Forbidden 頁碼)。

​​  在后置增強(qiáng)@AfterReturning中,限定了返回值類型,如果該請(qǐng)求響應(yīng)的類型是BaseResponse類型,則修改reponse消息體,附加通知信息;如果不是,則不處理,會(huì)等待下一個(gè)url請(qǐng)求,直到返回類型是BaseResponse類型。也可以采用自定義response的header的方式,這樣,就無需等待了。

​​  generateToken方法,是LoginService類的靜態(tài)方法,用于生成用戶token。

​​  至于Utility的parseRoles方法,是將bitmap編碼的roles解析為角色I(xiàn)D的列表,代碼如下:

//========================= 權(quán)限組合值解析 ======================================/** * * @methodName: parseRoles * @description: 解析角色組合值 * @param roles: 按位設(shè)置的角色組合值 * @return: 角色I(xiàn)D列表 * @history: * ------------------------------------------------------------------------------ * dateversionmodifierremarks* ------------------------------------------------------------------------------ * 2021/06/241.0.0sheng.zheng初版 * */ public static List<Integer> parseRoles(int roles){ List<Integer> roleList = new ArrayList<Integer>(); int newRoles = roles; int bit0 = 0; int roleId = 0; for (int i = 0; i < 32; i++) { //如果組合值的余位都為0,則跳出 if (newRoles == 0) { break; }//取得最后一位 bit0 = newRoles & 0x01; if (bit0 == 1) { //如果該位為1,左移i位 roleId = 1 << i; roleList.add(roleId); }//右移一位 newRoles = newRoles >> 1; } return roleList; }

​​  getRoleRights方法,是角色功能權(quán)限服務(wù)類RoleFuncRightsService的方法,它提供了根據(jù)List類型的角色I(xiàn)D列表,快速獲取功能權(quán)限樹的功能。​​  關(guān)于功能權(quán)限樹TreeNode類型,請(qǐng)參閱:《Java通用樹結(jié)構(gòu)數(shù)據(jù)管理》。

到此這篇關(guān)于Spring Boot動(dòng)態(tài)權(quán)限變更實(shí)現(xiàn)的整體方案的文章就介紹到這了,更多相關(guān)Spring Boot動(dòng)態(tài)權(quán)限內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 亚洲精品第五页 | 亚洲国产欧美自拍 | 精品一区二区三区在线观看l | 国产成人久久精品推最新 | 三级免费网站 | 免费观看欧美成人禁片 | 碰碰久久 | 一级欧美一级日韩毛片99 | 国产一级精品视频 | 亚洲人成亚洲人成在线观看 | 黄色毛片一级 | 欧洲成人在线 | 成年女人看片免费视频频 | 在线观看亚洲专区 | 5级做人爱c视版免费视频 | 国内久久久久影院精品 | 高清性色生活片欧美在线 | 亚洲三级视频在线观看 | 夜色成人性y | 日韩天天干 | 久久综合丁香 | 免费乱淫视频 | 99精品在线免费 | 亚洲第一页视频 | 国产免费久久精品 | 欧美日韩日本国产 | 久久精品成人欧美大片免费 | 欧美亚洲日本国产 | 国产亚洲一区二区三区不卡 | 国产成人毛片精品不卡在线 | 最新色网址 | 成年女人毛片免费播放人 | 国产一区中文字幕在线观看 | 国产成人免费片在线视频观看 | 久久久久久久久久久福利观看 | 欧美久久久久 | 国产成人禁片免费观看 | 久色乳综合思思在线视频 | 特级欧美午夜aa毛片 | 国产精品久久九九 | 国产成人综合网亚洲欧美在线 |