当前位置:JSON Web Tokens>相关文章>Go示例
手机访问

Go 语言 JWT 创建与解析示例

安装指南

首先要安装 jwt 包,首先需要安装 Go,然后可以使用以下命令在 Go 程序中添加 jwt-go 作为依赖项。

go get -u github.com/golang-jwt/jwt/v5

将其导入您的代码中:

import "github.com/golang-jwt/jwt/v5"

Examples

‌生成 JWT 令牌

使用HMAC签名方法创建、签名和编码JWT令牌的示例。

// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "foo": "bar",
    "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})

// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(hmacSampleSecret)

fmt.Println(tokenString, err)
Output:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>

解析 JWT 令牌

使用HMAC签名方法解析和验证令牌的示例。

// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"

// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
    // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
    return hmacSampleSecret, nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil {
    log.Fatal(err)
}

if claims, ok := token.Claims.(jwt.MapClaims); ok {
    fmt.Println(claims["foo"], claims["nbf"])
} else {
    fmt.Println(err)
}
Output:
bar 1.4444784e+09

更多用法

详细的使用指南,包括如何签署和验证令牌,可以在我们的文档网站上找到。

jwt.box3.cn