SoFunction
Updated on 2025-03-05

Detailed tutorial on using jwt in Go

generatetokenGenerally usedjwtThe two commonly used encryption methods areHS256andRS256, with the help of"/golang-jwt/jwt/v5"This library is implemented

jwtIt consists of three parts:

  • headerhead
    • Officially specified fields:
      • alg: (algorithm) algorithm
      • typ: (type) Type
      • cty: (content type) Content type
      • kid: (key ID) Key ID
      • x5u: (X.509 URL) X.509 Address
      • x5c: (X.509 certificate chain) X.509 certificate chain
      • crit: (critical) Essential
    • General usealgandtype,For example
{
  "alg": "HS256",
  "typ": "JWT"
}

payloadload

  • Officially stipulated fields
    • iss: (issuer) Issuer
    • exp: (expiration time) Expiration time
    • sub: (subject)
    • aud: (audience) Audience
    • nbf: (Not Before) Effective time
    • iat: (Issued At) Issued Time
    • jti: (JWT ID) Number
  • Custom fields
    • user: User information
  • For example
{
  "exp": 1718254332,
  "iat": 1718167932,
  "user": {
    "email": "jack@",
    "username": "jack22ssss22"
  }
}
  • signatureSignature, this signature cannot be leaked, otherwise it will be tampered with

CompletejwtIt's just to combine these three partsHMACSHA256(base64UrlEncode(Header).base64UrlEncode(Payload).Signature)

HS256 Encryption

HS256Is a symmetric encryption algorithm that uses a secret key to sign and verify each message

Generate tokens

func GenerateJWTHS256(username, email string) (string, error) {
  key := []byte("secret")
  tokenDuration := 24 * 
  now := ()
  t := (jwt.SigningMethodHS256, {
    "user": map[string]string{
      "username": username,
      "email":    email,
    },
    "iat": (),
    "exp": (tokenDuration).Unix(),
  })
  return (key)
}

Verify token

func VerifyJWTHS256(token string) (*, bool, error) {
  var claim 
  claims, err := (token, &claim, func(t *) (interface{}, error) {
    return []byte("secret"), nil
  })
  if err != nil {
    return nil, false, err
  }
  if  {
    return &claim, true, nil
  }
  return nil, false, nil
}

RS256 Encryption

RS256It is an asymmetric encryption algorithm that uses private key to encrypt plaintext and public key to decrypt ciphertext

Install openssl

apt install openssl

Generate rsa private key

Generate a in the current directory2048Bit's private key file

openssl genrsa -out  2048

Get the RSA key

var privateKey *
var publicKey *

func init() {
  var err error
  var bytes []byte
  bytes, err = ("/root/uccs/realworld/")
  if err != nil {
    panic(err)
  }
  privateKey, err = (bytes)
  if err != nil {
    panic(err)
  }

  bytes, err = ("/root/uccs/realworld/")
  if err != nil {
    panic(err)
  }
  publicKey, err = (bytes)
  if err != nil {
    panic(err)
  }
}

Generate tokens

func GenerateJWTRS256(username, email string) (string, error) {
  tokenDuration := 24 * 
  now := ()
  t := (jwt.SigningMethodRS256, {
    "user": map[string]string{
      "username": username,
      "email":    email,
    },
    "iat": (),
    "exp": (tokenDuration).Unix(),
  })
  return (privateKey)
}

Verify token

func VerifyJWTRS256(token string) (*, bool, error) {
  var claim 
  claims, err := (token, &claim, func(t *) (interface{}, error) {
    return publicKey, nil
  })
  if err != nil {
    return nil, false, err
  }
  if  {
    return &claim, true, nil
  }
  return nil, false, nil
}

The above is the detailed explanation of the tutorial on using jwt in Go. For more information about using jwt in Go, please follow my other related articles!