Spring Boot 通過AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法
本文介紹了Spring Boot 通過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ù)庫權(quán)限表中加入對(duì)應(yīng)接口需要的權(quán)限
- 用戶登錄時(shí),獲取當(dāng)前用戶的所有權(quán)限列表放入Redis緩存中
- 定義AOP,將切入點(diǎn)設(shè)置為自定義的權(quán)限
- AOP中獲取接口注解的權(quán)限值,和Redis中的數(shù)據(jù)校驗(yàn)用戶是否存在該權(quán)限,如果Redis中沒有,則從數(shù)據(jù)庫獲取用戶權(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ù)庫中添加對(duì)應(yīng)的記錄
* 用戶登錄時(shí),將用戶所有的權(quán)限列表放入redis中
* 用戶訪問接口時(shí),將對(duì)應(yīng)接口的值和redis中的匹配看是否有訪問權(quán)限
* 用戶退出登錄時(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)限的用戶才能訪問,否則提示非法操作
*/
@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是否過期或合法
- 獲取注解中的權(quán)限值,校驗(yàn)當(dāng)前用戶是否有訪問權(quán)限
- MongoDB 記錄訪問日志(IP、參數(shù)、接口、耗時(shí)等)
@Aspect
@Component
public class PermissionAspect {
/**
* 切入點(diǎn)
* 切入點(diǎn)為包路徑下的:execution(public * org.ylc.note.aop.controller..*(..)):
* org.ylc.note.aop.Controller包下任意類任意返回值的 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)方法封裝起來
* 具體驗(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是否已過期(解析信息或者redis中是否存在)
* */
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
throw new RuntimeException("非法請(qǐng)求,無效token");
}
// 校驗(yàn)token的業(yè)務(wù)邏輯
// ...
/*
* 獲取注解的值,并進(jìn)行權(quán)限驗(yàn)證:
* redis 中是否存在對(duì)應(yīng)的權(quán)限
* redis 中沒有則從數(shù)據(jù)庫中獲取權(quán)限
* 數(shù)據(jù)空中沒有,拋異常,非法請(qǐng)求,沒有權(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());
}
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring security密碼加密實(shí)現(xiàn)代碼實(shí)例
這篇文章主要介紹了Spring security密碼加密實(shí)現(xiàn)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
MyBatis-Plus實(shí)現(xiàn)字段自動(dòng)填充功能的示例
本文主要介紹了MyBatis-Plus實(shí)現(xiàn)字段自動(dòng)填充功能的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
SpringBoot項(xiàng)目Jar包如何瘦身部署的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot項(xiàng)目Jar包如何瘦身部署的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
使用Mybatis Generator結(jié)合Ant腳本快速自動(dòng)生成Model、Mapper等文件的方法
這篇文章主要介紹了使用Mybatis Generator結(jié)合Ant腳本快速自動(dòng)生成Model、Mapper等文件的方法的相關(guān)資料,需要的朋友可以參考下2016-06-06
Java 實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲框架詳細(xì)代碼
這篇文章主要介紹了Java 實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲框架,主要是用于爬取網(wǎng)絡(luò)上一些內(nèi)容,比如超鏈接之類的,需要的朋友可以參考下面文章內(nèi)容2021-09-09
SpringBoot項(xiàng)目配置明文密碼泄露問題的處理方式
這篇文章主要介紹了SpringBoot項(xiàng)目配置明文密碼泄露問題的處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06

