SoFunction
Updated on 2025-03-05

Detailed explanation of the steps to quickly implement JWT authentication in Go using go-zero

What is JWT, you can take a lookOfficial website, in one sentence, it is a stateless authentication solution that can realize servers and is also the most popular cross-domain authentication solution at present.

To implement JWT authentication, we need to divide it into the following two steps

  • The client gets the JWT token.
  • JWT token authentication brought by the server to the client.

1. Client obtains JWT Token

We define a protocol for the client to call to get the JWT token, we create a new directory jwt and execute it in the directorygoctl api -o , change the generated one to the following:

type JwtTokenRequest struct {
}

type JwtTokenResponse struct {
 AccessToken string `json:"access_token"`
 AccessExpire int64 `json:"access_expire"`
 RefreshAfter int64 `json:"refresh_after"` // It is recommended that the client refresh the token absolute time}

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 -dir .
Open the file and modify itfunc (l *JwtLogic) Jwt(req ) (*, error) {The method is as follows:

func (l *JwtLogic) Jwt(req ) (*, error) {
	var accessExpire = 

	now := ().Unix()
	accessToken, err := (now, , nil, accessExpire)
	if err != nil {
		return nil, err
	}

	return &{
 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()
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	for k, v := range payloads {
		claims[k] = v
	}

	token := (jwt.SigningMethodHS256)
	 = claims

	return ([]byte(secretKey))
}

Before starting the service, we need to modify the etc/file as follows:

Name: jwt-api
Host: 0.0.0.0
Port: 8888
JwtAuth:
 AccessSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 AccessExpire: 604800

Start the server and test the obtained 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. Server Verification JWT token

Pass in the api filejwt: JwtAuthThe service marked indicates that jwt authentication is activated. You can read the rest/handler/ file to understand the server jwt implementation. Modifications are as follows:

func (l *GetUserLogic) GetUser(req ) (*, error) {
	return &{Name: "kim"}, nil
}

Let's test the request header without JWT Authorization header, and return http status code is 401, which meets expectations.

➜ 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

Add Authorization header request header test.

➜ 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

To sum up: Go-zero-based JWT authentication is completed. When deploying in real production environments, AccessSecret, AccessExpire, RefreshAfter is configured through configuration files according to business scenarios. RefreshAfter tells the client when it is time to refresh the JWT token. Generally, it is necessary to set the expiration date a few days before.

3. Project address

/tal-tech/go-zero

Summarize

This is the article about how to quickly implement JWT certification in Go using go-zero. For more related content on go-zero to implement JWT certification, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!