AdSense

網頁

2024/4/7

Golang JWT HMAC-SHA256範例

Go使用jwt-go以HMAC-SHA256建立及驗證JWT Token範例。


範例環境:

  • Go 1.21

範例

main.go

package main

import (
    "fmt"
    "time"

    "github.com/golang-jwt/jwt/v5"
    "github.com/google/uuid"
)

type CustomClaims struct {
    jwt.RegisteredClaims
    Data Data `json:"data,omitempty"`
}

type Data map[string]any

func main() {
    now := time.Now()

    claims := CustomClaims{
        RegisteredClaims: jwt.RegisteredClaims{
            Issuer:    "abc.com",                                   // JWT簽發者
            IssuedAt:  jwt.NewNumericDate(now),                     // JWT發行時間
            NotBefore: jwt.NewNumericDate(now),                     // JWT有效期起始時間
            ExpiresAt: jwt.NewNumericDate(now.Add(24 * time.Hour)), // JWT過期時間
            Subject:   "john@abc.com",                              // JWT用戶
            ID:        uuid.New().String(),                         // JWT Token ID
            Audience:  jwt.ClaimStrings{"abc.com"},                 // JWT接收者
        },
        Data: Data{
            "name": "john",
            "age":  33,
        },
    }

    key := []byte("wtVFotSb10") // secret key
    tokenString, err := createToken(key, claims)
    if err != nil {
        panic(err)
    }

    fmt.Println(tokenString)

    parsedToken, err := parseToken(key, tokenString)
    if err != nil {
        panic(err)
    }
    custClaims := parsedToken.Claims.(*CustomClaims)
    fmt.Println(custClaims.Data)

}

func createToken(key []byte, claims jwt.Claims) (string, error) {
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, err := token.SignedString(key)
    if err != nil {
        return "", err
    }
    return tokenString, nil
}

func parseToken(key []byte, tokenString string) (*jwt.Token, error) {
    parsedToken, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return key, nil
    })
    if err != nil {
        panic(err)
    }
    return parsedToken, nil
}

github



測試

執行程式印出結果如下:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhYmMuY29tIiwic3ViIjoiam9obkBhYmMuY29tIiwiYXVkIjpbImFiYy5jb20iXSwiZXhwIjoxNzEyNjQyNjA4LCJuYmYiOjE3MTI1NTYyMDgsImlhdCI6MTcxMjU1NjIwOCwianRpIjoiMjc3NDRiM2EtMzRjNS00MmM3LWJhZTEtYzMzNzljYTFmOGEzIiwiZGF0YSI6eyJhZ2UiOjMzLCJuYW1lIjoiam9obiJ9fQ.BIQfrydtJeBXRykHf8g_tcwPV3UYc01haZe6dKbIpV4
map[age:33 name:john]


沒有留言:

AdSense