利用go-zero在Go中快速實現(xiàn)JWT認(rèn)證的步驟詳解
關(guān)于JWT是什么,大家可以看看官網(wǎng),一句話介紹下:是可以實現(xiàn)服務(wù)器無狀態(tài)的鑒權(quán)認(rèn)證方案,也是目前最流行的跨域認(rèn)證解決方案。
要實現(xiàn)JWT認(rèn)證,我們需要分成如下兩個步驟
- 客戶端獲取JWT token。
- 服務(wù)器對客戶端帶來的JWT token認(rèn)證。
1. 客戶端獲取JWT Token
我們定義一個協(xié)議供客戶端調(diào)用獲取JWT token,我們新建一個目錄jwt然后在目錄中執(zhí)行 goctl api -o jwt.api,將生成的jwt.api改成如下:
type JwtTokenRequest struct {
}
type JwtTokenResponse struct {
AccessToken string `json:"access_token"`
AccessExpire int64 `json:"access_expire"`
RefreshAfter int64 `json:"refresh_after"` // 建議客戶端刷新token的絕對時間
}
type GetUserRequest struct {
UserId string `json:"userId"`
}
type GetUserResponse struct {
Name string `json:"name"`
}
service jwt-api {
@handler JwtHandler
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
}
@server(
jwt: JwtAuth
)
service jwt-api {
@handler JwtHandler
post /user/info(GetUserRequest) returns (GetUserResponse)
}
在服務(wù)jwt目錄中執(zhí)行:goctl api go -api jwt.api -dir .
打開jwtlogic.go文件,修改 func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) { 方法如下:
func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) {
var accessExpire = l.svcCtx.Config.JwtAuth.AccessExpire
now := time.Now().Unix()
accessToken, err := l.GenToken(now, l.svcCtx.Config.JwtAuth.AccessSecret, nil, accessExpire)
if err != nil {
return nil, err
}
return &types.JwtTokenResponse{
AccessToken: accessToken,
AccessExpire: now + accessExpire,
RefreshAfter: now + accessExpire/2,
}, nil
}
func (l *JwtLogic) GenToken(iat int64, secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
for k, v := range payloads {
claims[k] = v
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}
在啟動服務(wù)之前,我們需要修改etc/jwt-api.yaml文件如下:
Name: jwt-api Host: 0.0.0.0 Port: 8888 JwtAuth: AccessSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx AccessExpire: 604800
啟動服務(wù)器,然后測試下獲取到的token。
➜ curl --location --request POST '127.0.0.1:8888/user/token'
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc","access_expire":1601261429,"refresh_after":1600959029}
2. 服務(wù)器驗證JWT token
在api文件中通過jwt: JwtAuth標(biāo)記的service表示激活了jwt認(rèn)證??梢蚤喿xrest/handler/authhandler.go文件了解服務(wù)器jwt實現(xiàn)。修改getuserlogic.go如下:
func (l *GetUserLogic) GetUser(req types.GetUserRequest) (*types.GetUserResponse, error) {
return &types.GetUserResponse{Name: "kim"}, nil
}
我們先不帶JWT Authorization header請求頭測試下,返回http status code是401,符合預(yù)期。
➜ curl -w "\nhttp: %{http_code} \n" --location --request POST '127.0.0.1:8888/user/info' \
--header 'Content-Type: application/json' \
--data-raw '{
"userId": "a"
}'
http: 401
加上Authorization header請求頭測試。
➜ curl -w "\nhttp: %{http_code} \n" --location --request POST '127.0.0.1:8888/user/info' \
--header 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc' \
--header 'Content-Type: application/json' \
--data-raw '{
"userId": "a"
}'
{"name":"kim"}
http: 200
綜上所述:基于go-zero的JWT認(rèn)證完成,在真實生產(chǎn)環(huán)境部署時候,AccessSecret, AccessExpire, RefreshAfter根據(jù)業(yè)務(wù)場景通過配置文件配置,RefreshAfter 是告訴客戶端什么時候該刷新JWT token了,一般都需要設(shè)置過期時間前幾天。
3. 項目地址
https://github.com/tal-tech/go-zero
總結(jié)
到此這篇關(guān)于如何利用go-zero在Go中快速實現(xiàn)JWT認(rèn)證的文章就介紹到這了,更多相關(guān)go-zero實現(xiàn)JWT認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go?數(shù)據(jù)結(jié)構(gòu)之二叉樹詳情
這篇文章主要介紹了?Go?數(shù)據(jù)結(jié)構(gòu)之二叉樹詳情,二叉樹是一種數(shù)據(jù)結(jié)構(gòu),在每個節(jié)點下面最多存在兩個其他節(jié)點。即一個節(jié)點要么連接至一個、兩個節(jié)點或不連接其他節(jié)點,下文基于GO語言展開二叉樹結(jié)構(gòu)詳情,需要的朋友可以參考一下2022-05-05
golang實現(xiàn)單點登錄系統(tǒng)(go-sso)
這篇文章主要介紹了golang實現(xiàn)單點登錄系統(tǒng)(go-sso),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06

