Spring Boot+Spring Security+JWT 實現 RESTful Api 認證(一)


標題

Spring Boot+Spring Security+JWT 實現 RESTful Api 認證(一)

技術

Spring Boot 2、Spring Security 5、JWT

運行環境

IDEA+JDK8.0+MySQL5.0+

簡述

Spring Boot 2 + Spring Security 5 + JWT 實現給RestApi增加認證控制

測試流程

下面對我們的程序進行簡單的驗證

1.請求獲取用戶列表接口:http://localhost:8080/users/userList接口,會收到401錯誤

{
"timestamp": 1567564486909,
"status": 401,
"error": "Unauthorized",
"message": "Full authentication is required to access this resource",
"path": "/users/userList"
}
curl http://localhost:8080/users/userList

原因就是因為這個url沒有授權,所以返回401

輸入圖片說明

2.注冊一個新用戶

curl -H "Content-Type: application/json" -X POST -d '{

"username": "admin",

"password": "password"

}' http://localhost:8080/users/signup

輸入圖片說明

3.登錄,會返回token,在http header中,Authorization: Bearer 后面的部分就是token

curl -i -H "Content-Type: application/json" -X POST -d '{

"username": "admin",

"password": "password"

}' http://localhost:8080/login

溫馨提醒:這里的login方法是spring specurity框架提供的默認登錄url
輸入圖片說明

4.用登錄成功后拿到的token再次請求/users/userList接口

4.1將請求中的XXXXXX替換成拿到的token

4.2這次可以成功調用接口了

curl -H "Content-Type: application/json"

-H "Authorization: Bearer XXXXXX"

"http://localhost:8080/users/userList"
輸入圖片說明

5.設置了1分鍾后Token過期,如果1分鍾后再次請求/users/userList接口返回Token過期的異常提示如下圖:

輸入圖片說明

6.集成Swagger-ui,方便前后端分離開發,默認訪問地址:http://localhost:8080/swagger-ui.html

輸入圖片說明
輸入圖片說明
輸入圖片說明
溫馨提示:這里的登錄接口還是使用的默認地址,如果你的token過期了,需要你重新登錄生成新的token.

下載地址

https://gitee.com/micai-code/springboot-springsecurity-jwt-demo.git

結束語

在使用的過程中,如有問題,可以添加真正討論技術的QQ交流群,QQ群號為:715224124


免責聲明!

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



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