In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use go-zero to achieve JWT authentication in Go, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand it.
1. Client gets JWT Token
We define a protocol for the client to call to get JWT token. We create a new directory jwt and execute goctl api-o jwt.api in the directory. Change the generated jwt.api to the following:
Type JwtTokenRequest struct {} type JwtTokenResponse struct {AccessToken string `json: "access_token" `AccessExpire int64 `json: "access_expire" `RefreshAfter int64 `json: "refresh_after" `/ recommended absolute time for clients to refresh 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)}
Execute in the service jwt directory: goctl api go-api jwt.api-dir. Open the jwtlogic.go file and modify func (l * JwtLogic) Jwt (req types.JwtTokenRequest) (* types.JwtTokenResponse, error) {as follows:
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))}
Before starting the service, we need to modify the etc/jwt-api.yaml file as follows:
Name: jwt-apiHost: 0.0.0.0Port: 8888JwtAuth: AccessSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx AccessExpire: 604800
Start the server and test the obtained token.
➜curl-- location-- request POST '127.0.0.1 request POST' 127.0.0.1user access_token'{"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc", "access_expire": 1601261429, "refresh_after": 1600959029} 2. Server verifies JWT token
The service of the jwt: JwtAuth tag in the api file indicates that jwt authentication is activated.
You can read the rest/handler/authhandler.go file to understand the server jwt implementation.
Modify the getuserlogic.go as follows:
Func (l * GetUserLogic) GetUser (req types.GetUserRequest) (* types.GetUserResponse, error) {return & types.GetUserResponse {Name: "kim"}, nil}
We first test without the JWT Authorization header request header, and the return http status code is 401, as expected.
➜curl-w "\ nhttp:% {http_code}\ n"-- location-- request POST '127.0.0.1 purge 8888max user info'\-header' Content-Type: application/json'\-- data-raw'{"userId": "a"} 'http: 401
Plus the Authorization header request header test.
➜curl-w "\ nhttp:% {http_code}\ n"-- location-- request POST '127.0.0.1 location'-- header 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc'\-- header' Content-Type: application/json':-- data-raw'{"userId": "a"}'{"name": "kim"} http: 200
To sum up: the JWT authentication based on go-zero is completed. When deploying in a real production environment, AccessSecret, AccessExpire, and RefreshAfter are configured through configuration files according to business scenarios. RefreshAfter tells the client when to refresh JWT token. Generally, you need to set the expiration time a few days before.
Thank you for reading this article carefully. I hope the article "how to use go-zero to achieve JWT certification in Go" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.