Golang Engineering Components Lightweight Authentication Mechanism jwt Lightweight Authentication Mechanism jwt

In web applications, authentication and authorization are very important. JWT (JSON Web Token) is a lightweight authentication mechanism that can perform secure authentication without cookies or sessions. This article will introduce the basic concept of JWT, how it works, and how to use JWT in Golang.

  1. Basic concept of JWT

JWT consists of three parts: header, payload and signature. They are all Base64-encoded strings and concatenated by period separators.

The header contains information such as identifying the token type and the encryption algorithm used; the payload stores relevant information such as user ID and expiration time; the signature uses the server-side key to encrypt the first two parts to ensure that the token has not been tampered with Pass.

  1. How JWTs work

When the user logs in successfully, the server generates a JWT and sends it to the client. The client needs to bring this token with each request, and the corresponding resource can only be accessed after verification by the server.

Here is the whole process:

  • After the user logs in successfully, the server generates a JWT for the user.
  • The server returns that JWT to the client.
  • The client needs to bring the JWT with each request.
  • The server verifies the JWT and determines whether the user has permission to access the corresponding resource.
  1. Using JWT in Golang

In Golang, we can use the third-party package http://github.com/dgrijalva/jwt-go to realize the generation and verification of JWT.

Here is a simple example:

package main

import (
    "fmt"
    "time"

    "github.com/dgrijalva/jwt-go"
)

func main() {
    // 创建一个JWT
    token := jwt.New(jwt.SigningMethodHS256)

    // 设置一些标准声明
    claims := token.Claims.(jwt.MapClaims)
    claims["sub"] = "1234567890"
    claims["name"] = "John Doe"
    claims["iat"] = time.Now().Unix()
    claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

    // 签名并获取完整的编码后的字符串token
    secretKey := []byte("my_secret_key")
    signedToken, err := token.SignedString(secretKey)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(signedToken)

   // 解析并验证JWT
   parsedToken, err := jwt.Parse(signedToken, func(token *jwt.Token) (interface{}, error) {
       if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
           return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
       }

       return secretKey, nil
   })

   if parsedToken.Valid {
       fmt.Println("Valid JWT")
   } else if ve, ok := err.(*jwt.ValidationError); ok {
       if ve.Errors&jwt.ValidationErrorMalformed != 0 {
           fmt.Println("Invalid JWT format")
       } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
           fmt.Println("JWT is either expired or not valid yet")
       } else {
           fmt.Println("Unable to parse JWT")
       }
   } else {
       fmt.Println("Unable to parse JWT")
   }
}

In this example, we first create a JWT and set some standard claims. We then sign the JWT with the key and get the full encoded string token.

Next, we parsed and verified the JWT. If the verification is passed, output "Valid JWT"; otherwise, output the corresponding information according to the error type.

Summarize

JWT is a lightweight authentication mechanism that can perform secure authentication without the need for cookies or sessions. Using the third-party package http://github.com/dgrijalva/jwt-go in Golang can easily realize the generation and verification of JWT. Of course, in practical applications, we also need to pay attention to the encryption algorithm, key length and other related details, and reasonably handle various abnormal situations.

Guess you like

Origin blog.csdn.net/SMILY12138/article/details/130946884