Spring Boot 通過(guò)AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法
本文介紹了Spring Boot 通過(guò)AOP和自定義注解實(shí)現(xiàn)權(quán)限控制,分享給大家,具體如下:
源碼:https://github.com/yulc-coding/java-note/tree/master/aop
思路
- 自定義權(quán)限注解
- 在需要驗(yàn)證的接口上加上注解,并設(shè)置具體權(quán)限值
- 數(shù)據(jù)庫(kù)權(quán)限表中加入對(duì)應(yīng)接口需要的權(quán)限
- 用戶(hù)登錄時(shí),獲取當(dāng)前用戶(hù)的所有權(quán)限列表放入Redis緩存中
- 定義AOP,將切入點(diǎn)設(shè)置為自定義的權(quán)限
- AOP中獲取接口注解的權(quán)限值,和Redis中的數(shù)據(jù)校驗(yàn)用戶(hù)是否存在該權(quán)限,如果Redis中沒(méi)有,則從數(shù)據(jù)庫(kù)獲取用戶(hù)權(quán)限列表,再校驗(yàn)
pom文件 引入AOP
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- AOP 切面--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
自定義注解 VisitPermission
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface VisitPermission { /** * 用于配置具體接口的權(quán)限值 * 在數(shù)據(jù)庫(kù)中添加對(duì)應(yīng)的記錄 * 用戶(hù)登錄時(shí),將用戶(hù)所有的權(quán)限列表放入redis中 * 用戶(hù)訪問(wèn)接口時(shí),將對(duì)應(yīng)接口的值和redis中的匹配看是否有訪問(wèn)權(quán)限 * 用戶(hù)退出登錄時(shí),清空redis中對(duì)應(yīng)的權(quán)限緩存 */ String value() default ""; }
需要設(shè)置權(quán)限的接口上加入注解 @VisitPermission(value)
@RestController @RequestMapping("/permission") public class PermissionController { /** * 配置權(quán)限注解 @VisitPermission("permission-test") * 只用擁有該權(quán)限的用戶(hù)才能訪問(wèn),否則提示非法操作 */ @VisitPermission("permission-test") @GetMapping("/test") public String test() { System.out.println("================== step 3: doing =================="); return "success"; } }
定義權(quán)限AOP
- 設(shè)置切入點(diǎn)為@annotation(VisitPermission)
- 獲取請(qǐng)求中的token,校驗(yàn)是否token是否過(guò)期或合法
- 獲取注解中的權(quán)限值,校驗(yàn)當(dāng)前用戶(hù)是否有訪問(wèn)權(quán)限
- MongoDB 記錄訪問(wèn)日志(IP、參數(shù)、接口、耗時(shí)等)
@Aspect @Component public class PermissionAspect { /** * 切入點(diǎn) * 切入點(diǎn)為包路徑下的:execution(public * org.ylc.note.aop.controller..*(..)): * org.ylc.note.aop.Controller包下任意類(lèi)任意返回值的 public 的方法 * <p> * 切入點(diǎn)為注解的: @annotation(VisitPermission) * 存在 VisitPermission 注解的方法 */ @Pointcut("@annotation(org.ylc.note.aop.annotation.VisitPermission)") private void permission() { } /** * 目標(biāo)方法調(diào)用之前執(zhí)行 */ @Before("permission()") public void doBefore() { System.out.println("================== step 2: before =================="); } /** * 目標(biāo)方法調(diào)用之后執(zhí)行 */ @After("permission()") public void doAfter() { System.out.println("================== step 4: after =================="); } /** * 環(huán)繞 * 會(huì)將目標(biāo)方法封裝起來(lái) * 具體驗(yàn)證業(yè)務(wù)數(shù)據(jù) */ @Around("permission()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("================== step 1: around =================="); long startTime = System.currentTimeMillis(); /* * 獲取當(dāng)前http請(qǐng)求中的token * 解析token : * 1、token是否存在 * 2、token格式是否正確 * 3、token是否已過(guò)期(解析信息或者redis中是否存在) * */ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String token = request.getHeader("token"); if (StringUtils.isEmpty(token)) { throw new RuntimeException("非法請(qǐng)求,無(wú)效token"); } // 校驗(yàn)token的業(yè)務(wù)邏輯 // ... /* * 獲取注解的值,并進(jìn)行權(quán)限驗(yàn)證: * redis 中是否存在對(duì)應(yīng)的權(quán)限 * redis 中沒(méi)有則從數(shù)據(jù)庫(kù)中獲取權(quán)限 * 數(shù)據(jù)空中沒(méi)有,拋異常,非法請(qǐng)求,沒(méi)有權(quán)限 * */ Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); VisitPermission visitPermission = method.getAnnotation(VisitPermission.class); String value = visitPermission.value(); // 校驗(yàn)權(quán)限的業(yè)務(wù)邏輯 // List<Object> permissions = redis.get(permission) // db.getPermission // permissions.contains(value) // ... System.out.println(value); // 執(zhí)行具體方法 Object result = proceedingJoinPoint.proceed(); long endTime = System.currentTimeMillis(); /* * 記錄相關(guān)執(zhí)行結(jié)果 * 可以存入MongoDB 后期做數(shù)據(jù)分析 * */ // 打印請(qǐng)求 url System.out.println("URL : " + request.getRequestURL().toString()); // 打印 Http method System.out.println("HTTP Method : " + request.getMethod()); // 打印調(diào)用 controller 的全路徑以及執(zhí)行方法 System.out.println("controller : " + proceedingJoinPoint.getSignature().getDeclaringTypeName()); // 調(diào)用方法 System.out.println("Method : " + proceedingJoinPoint.getSignature().getName()); // 執(zhí)行耗時(shí) System.out.println("cost-time : " + (endTime - startTime) + " ms"); return result; } }
單元測(cè)試
package org.ylc.note.aop; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.ylc.note.aop.controller.PermissionController; @SpringBootTest class AopApplicationTests { @Autowired private PermissionController permissionController; private MockMvc mvc; @BeforeEach void setupMockMvc() { mvc = MockMvcBuilders.standaloneSetup(permissionController).build(); } @Test void apiTest() throws Exception { MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/permission/test") .accept(MediaType.APPLICATION_JSON) .header("token", "9527")) .andReturn(); System.out.println("api test result : " + result.getResponse().getContentAsString()); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解析Java中未被捕獲的異常以及try語(yǔ)句的嵌套使用
這篇文章主要介紹了Java中未被捕獲的異常以及try語(yǔ)句的嵌套使用,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09每日六道java新手入門(mén)面試題,通往自由的道路--多線(xiàn)程
這篇文章主要為大家分享了最有價(jià)值的6道多線(xiàn)程面試題,涵蓋內(nèi)容全面,包括數(shù)據(jù)結(jié)構(gòu)和算法相關(guān)的題目、經(jīng)典面試編程題等,對(duì)hashCode方法的設(shè)計(jì)、垃圾收集的堆和代進(jìn)行剖析,感興趣的小伙伴們可以參考一下2021-06-06Java使用單鏈表實(shí)現(xiàn)約瑟夫環(huán)
這篇文章主要為大家詳細(xì)介紹了Java使用單鏈表實(shí)現(xiàn)約瑟夫環(huán),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10Java中駝峰命名與下劃線(xiàn)命名相互轉(zhuǎn)換
這篇文章主要介紹了Java中駝峰命名與下劃線(xiàn)命名相互轉(zhuǎn)換,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01java工具類(lèi)之實(shí)現(xiàn)java獲取文件行數(shù)
這篇文章主要介紹了一個(gè)java工具類(lèi),可以取得當(dāng)前項(xiàng)目中所有java文件總行數(shù),代碼行數(shù),注釋行數(shù),空白行數(shù),需要的朋友可以參考下2014-03-03解決mybatis 中collection嵌套collection引發(fā)的bug
這篇文章主要介紹了解決mybatis 中collection嵌套collection引發(fā)的bug,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12java8 Instant 時(shí)間及轉(zhuǎn)換操作
這篇文章主要介紹了java8 Instant 時(shí)間及轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09