SoFunction
Updated on 2025-03-03

Go-micro microservice JWT cross-domain authentication problem

1 JWT Introduction

JWT's English name is Json Web Token, which is a concise, URL-safe expressive declaration specification used to transfer secure information between the two parties of the communication, and is often used for cross-domain authentication.

JWT safely passes information in the form of a JSON object. Because there is a digital signature, the information passed is secure.

A JWT Token looks like this:

eyJhbGci0iJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyODAx0DcyNzQ40DMyMzU4NSwiZ
XhwIjoxNTk0NTQwMjkxLCJpc3MiOiJibHV1YmVsbCJ9.1k_ZrAtYGCeZhK3iupHxP1kgjBJzQTVTtX0iZYFx9wU

It is composed of three parts separated by ., which are in turn:

  • Header
  • Payload
  • Signature

The header and load exist in jSON form, which is JSON in JWT. The contents of the three parts have been edited separately by Base64.
Code to splice into a JWT Token.

2. Pros and cons of JWT

JWT has all the advantages of Token-based session management, and does not rely on cookies, so that it can prevent CSRF attacks.
Click to run normally in a browser environment with cookies disabled.

The biggest advantage of JWT is that the server no longer needs to store the session, so that the server authentication and authentication service can be easily expanded and avoid storage
The components such as Redis required to be introduced in Session reduce the complexity of the system architecture. But this is also the biggest disadvantage of JWT, due to the validity period
Stored in the token. Once the JWT token is issued, it will be available for the validity period and cannot be abolished on the server side. When the user logs in
When the operation is released, you can only rely on the client to delete the locally stored JWT token. If you need to disable the user, you cannot do it simply by using JWT.

Three JWT use

1. Packet and data definition

package token

import (
   "account/config/redis"
   "errors"
   "fmt"
   "/dgrijalva/jwt-go"
   "time"
)

// MyClaims custom declare structure and embedded// The jwt package comes with only official fields// We need to record an additional username field here, so we need to customize the structure// If you want to save more information, you can add it to this structuretype MyClaims struct {
   UserName string `json:"username"`
   
}

const TokenExpireDuration =  * 2

var MySecret = []byte("Account")

2. Generate JWT

// GenToken generates JWTfunc GenToken(UserName string) (string, error) {
   // Create a statement of our own   c := MyClaims{
      UserName, // Custom fields      {
         ExpiresAt: ().Add(TokenExpireDuration).Unix(), // Expiry time         Issuer:    "Account",                                  // Issuer      },
   }
   // Create a signed object using the specified signature method   token := (jwt.SigningMethodHS256, c)
   // Sign with the specified secret and get the full encoded string token   return (MySecret)
}

3. Analyze JWT

// ParseToken parses JWTfunc ParseToken(tokenString string) (*MyClaims, error) {
   // parse token   var mc = new(MyClaims)
   token, err := (tokenString, mc, func(token *) (i interface{}, err error) {
      return MySecret, nil
   })
   if err != nil {
      return nil, err
   }
   if  { // Verify token      return mc, nil
   }
   return nil, ("invalid token")
}

4. Complete code

package token

import (
   "account/config/redis"
   "errors"
   "fmt"
   "/dgrijalva/jwt-go"
   "time"
)

// MyClaims custom declare structure and embedded// The jwt package comes with only official fields// We need to record an additional username field here, so we need to customize the structure// If you want to save more information, you can add it to this structuretype MyClaims struct {
   UserName string `json:"username"`
   
}

const TokenExpireDuration =  * 2

var MySecret = []byte("Account")

// GenToken generates JWTfunc GenToken(UserName string) (string, error) {
   // Create a statement of our own   c := MyClaims{
      UserName, // Custom fields      {
         ExpiresAt: ().Add(TokenExpireDuration).Unix(), // Expiry time         Issuer:    "Account",                                  // Issuer      },
   }
   // Create a signed object using the specified signature method   token := (jwt.SigningMethodHS256, c)
   // Sign with the specified secret and get the full encoded string token   return (MySecret)
}

// ParseToken parses JWTfunc ParseToken(tokenString string) (*MyClaims, error) {
   // parse token   var mc = new(MyClaims)
   token, err := (tokenString, mc, func(token *) (i interface{}, err error) {
      return MySecret, nil
   })
   if err != nil {
      return nil, err
   }
   if  { // Verify token      return mc, nil
   }
   return nil, ("invalid token")
}

Four Last

  • At this point, the cross-domain authentication of go-micro microservices JWT has been officially completed.

  • Next, we start writing the code of public functions. I hope everyone will follow the blogger and the columns to get the latest content as soon as possible. Every blog is full of practical information.

This is the article about JWT cross-domain authentication of go-micro microservices. For more related go-micro microservices, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!