怎麼在SpringBoot中使用Spring AOP實作介面鑑權
面向切面編程
面向切面編程,可以將與業務無關但是需要被各個業務模組共同調用的邏輯抽取出來,以切面的方式切入到代碼中,從而降低系統中代碼的耦合度,減少重複的程式碼。
Spring AOP是透過預編譯方式和運行期間動態代理實現程式面向切面程式設計
AOP的底層原理實作
AOP底層使用動態代理完成需求,為需要增加增強功能的類別來產生代理類,有兩種產生代理類別的方式,對於被代理類別(即需要增強的類別),如果:
#實作了接口,使用JDK動態代理,產生的代理類別會使用其介面沒有實作接口,
使用CGlib動態代理,產生的代理類別會整合被代理類別
AOP的相關術語
#連接點:在被代理(被增強)的類別中的方法
切入點:實際上需要被增強的方法
##通知:要增強的邏輯代碼
前通知:在主體功能執行前執行
後置通知:在主題功能執行之後執行
環繞通知:在主體功能執行前後執行
#異常通知:在主題功能執行出現異常時執行
#最終通知:主體功能無論執行是否成功都會執行
切面:切入點和切面的結合,即被增強的方法和增強的功能組成切面
註解:
#@Aspect: 宣告某個類別是切面,寫通知、切入點
@Before: 對應前置通知
@AfterReturning: 對應後置通知
@Around: 對應環繞通知
- ##@AfterThrowing:
對應例外通知
- @After:
對應最終通知
- @Pointcut:
聲明切入點,標註在一個方法上可以讓表達式更簡潔
- execution([權限修飾符][傳回類型][類別完全路徑].[方法名稱][參數清單類型])
- execution(* com.xxx.ABC. add()),對ABC類別的方法進行增強
實作介面鑑權
1. 設定yml檔案
設定介面鑑權帳密2. 讀取帳密配置account: infos: - account: xinchao secret: admin登入後複製
@Data public class SecretInfo { private String account; private String secret; }
3.寫介面鑑權方法
@Configuration @ConfigurationProperties("account") public class SecretConfig { private List<SecretInfo> infos; private Map<String, SecretInfo> map; private Map<String, TokenInfo> tokenMap = new HashMap<>(); public void setInfos(List<SecretInfo> infos) { this.infos = infos; map = infos.stream().collect(Collectors.toMap(SecretInfo::getAccount, Function.identity())); } public synchronized String getToken(String account, String secret) { SecretInfo info = map.get(account); if (info == null) { throw new BusinessException("无效账号"); } if (!StringUtils.equals(info.getSecret(), secret)) { throw new BusinessException("无效密码"); } TokenInfo tokenInfo = tokenMap.get(account); if (tokenInfo != null && tokenInfo.getToken() != null) { return tokenInfo.getToken(); } tokenInfo = new TokenInfo(); String uuid = UUID.randomUUID().toString(); tokenInfo.setToken(uuid); tokenInfo.setCreateDate(LocalDateTime.now()); tokenInfo.setExpireDate(LocalDateTime.now().plusHours(2)); tokenMap.put(account,tokenInfo); return tokenInfo.getToken(); } public boolean checkCaptcha(String captcha) { return tokenMap.values().stream().anyMatch(e->StringUtils.equals(e.getToken(),captcha)); } }
@Data public class TokenInfo { private LocalDateTime createDate; private LocalDateTime expireDate; private String token; public String getToken() { if (LocalDateTime.now().isBefore(expireDate)) { return token; } return null; } public boolean verification(String token) { return Objects.equals(this.token, token); } }
4. 寫AOP
首先,編寫一個註解來標識不需要鑑權@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CaptchaIgnoreAop { }登入後複製5.編寫介面測試@Slf4j @Aspect @Component @Order(2) public class CaptchaAop { @Value("${spring.profiles.active:dev}") private String env; @Autowired private SecretConfig config; @Pointcut("execution(public * com.herenit.phsswitch.controller.impl..*.*(..))" + "&&@annotation(org.springframework.web.bind.annotation.PostMapping)" + "&&!@annotation(com.herenit.phsswitch.aop.CaptchaIgnoreAop)") public void tokenAop() { } @Around("tokenAop()") public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); if (args.length == 0 || !(args[0] instanceof RequestWrapper) || "test,dev".contains(env)) { log.info("当前环境无需校验token"); return joinPoint.proceed(); } String captcha = ((RequestWrapper) joinPoint.getArgs()[0]).getCaptcha(); if (!config.checkCaptcha(captcha)) { throw new BusinessException("captcha无效"); } return joinPoint.proceed(); } }登入後複製
@PostMapping("/login") @CaptchaIgnoreAop public ResponseWrapper login(@RequestBody JSONObject userInfo) { String token = config.getToken(userInfo.getString("loginName") , userInfo.getString("password")); JSONObject result = new JSONObject(); result.put("platformAccessToken", token); return ResponseWrapper.success(result); }
使用此介面能夠在記憶體中建立一個令牌,並將其傳回給前端。之後我們在調其他介面時傳入這個token進行鑑權即可。傳入的位置是captcha字段
public class RequestWrapper<T> implements Serializable { private static final long serialVersionUID = 8988706670118918321L; public RequestWrapper() { super(); } private T args; private String captcha; private String funcode; public T getArgs() { return args; } public void setArgs(T args) { this.args = args; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } public String getFuncode() { return funcode; } public void setFuncode(String funcode) { this.funcode = funcode; } }
以上是怎麼在SpringBoot中使用Spring AOP實作介面鑑權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

2023年,AI技術已成為熱門話題,對各行業產生了巨大影響,程式設計領域尤其如此。人們越來越認識到AI技術的重要性,Spring社群也不例外。隨著GenAI(GeneralArtificialIntelligence)技術的不斷進步,簡化具備AI功能的應用程式的創建變得至關重要和迫切。在這個背景下,"SpringAI"應運而生,旨在簡化開發AI功能應用程式的過程,使其變得簡單直觀,避免不必要的複雜性。透過"SpringAI",開發者可以更輕鬆地建立具備AI功能的應用程序,將其變得更加易於使用和操作

Spring+AI作為行業領導者,透過其強大、靈活的API和先進的功能,為各種行業提供了領先性的解決方案。在本專題中,我們將深入探討Spring+AI在各領域的應用範例,每個案例都將展示Spring+AI如何滿足特定需求,實現目標,並將這些LESSONSLEARNED擴展到更廣泛的應用。希望這個專題能對你有所啟發,更深入地理解和利用Spring+AI的無限可能。 Spring框架在軟體開發領域已經有超過20年的歷史,自SpringBoot1.0版本發布以來已有10年。現在,無人會質疑,Spring

spring編程式事務的實作方式:1、使用TransactionTemplate;2、使用TransactionCallback和TransactionCallbackWithoutResult;3、使用Transactional註解;4、使用TransactionTemplate和@Transactional結合使用;5、自訂事務管理器。

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

本文來寫個詳細的例子來說下dubbo+nacos+Spring Boot開發實戰。本文不會講述太多的理論的知識,會寫一個最簡單的例子來說明dubbo如何與nacos整合,快速建構開發環境。

Spring設定事務隔離等級的方法:1、使用@Transactional註解;2、在Spring設定檔中設定;3、使用PlatformTransactionManager;4、在Java配置類別中設定。詳細介紹:1、使用@Transactional註解,在需要進行事務管理的類別或方法上加入@Transactional註解,並在屬性中設定隔離等級;2、在Spring設定檔等等。

Spring是一個開源框架,提供了許多註解來簡化和增強Java開發。本文將詳細解釋常用的Spring註解,並提供具體的程式碼範例。 @Autowired:自動組裝@Autowired註解可以用於自動組裝Spring容器中的Bean。當我們在需要依賴的地方使用@Autowired註解時,Spring將會在容器中尋找匹配的Bean並自動注入。範例程式碼如下:@Auto

Spring中Bean取得方式詳解在Spring框架中,Bean的取得是非常重要的一環。在應用程式中,我們經常需要使用依賴注入或動態來取得Bean的實例。本文將詳細介紹Spring中Bean的取得方式,並給出具體的程式碼範例。透過@Component註解取得Bean@Component註解是Spring框架中常用的註解之一。我們可以透過在類別上新增@Compone
