標題
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/166189.html
標籤:其他
