SpringSecurity整合Jwt


一、創建項目並導入依賴

   

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>io.jsonwebtoken</groupId>

<artifactId>jjwt</artifactId>

<version>0.9.1</version>

</dependency>

   

二、相關配置和代碼

不了解jwt的建議先去看一下這篇,看完理論更好理解

https://www.jianshu.com/p/99a458c62aa4

   

2.1)要想實現jwt,需要兩個過濾器。一是用戶登陸成功是給他返回加密后的jwt數據格式,密鑰存在服務端secret

二是校驗客戶端訪問時攜帶token

   

2.2)創建jwt的登陸過濾器實現AbstractAuthenticationProcessingFilter

   

   

2.3)重寫父類方法

   

   

   

   

   

2.4)創建客戶端訪問時攜帶的token校驗過濾器

   

   

這也恰恰說明,jwt數據不是一定要攜帶賬戶密碼角色的,只要能驗證身份就行因為TOKEN本身就好似密碼。這里帶用戶信息是為了springsecurity

具體可以根據自己業務設計

   

   

2.5)創建SecurityConfig配置類,里面的配置就不解釋了,不理解翻我以前的博客

   

   

2.6)controller

   

   

三、測試效果圖

   

3.1)先登錄

   

   

3.2)使用給我們的token去訪問

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM