go開源庫之jwt-go使用

attitude發表於2021-04-14

開源庫地址:
jwt-go

該包支援多種加密方式,我們這裡使用HS256進行演示

  • 專案中下載工具包
go get -u github.com/dgrijalva/jwt-go
  • 生成token
mySigningKey := []byte("AllYourBase")

// Create the Claims
claims := &jwt.StandardClaims{
    ExpiresAt: 15000, // reqiured
    Issuer:    "test",
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
sToken, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", sToken, err)
  • 解析token
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

type MyCustomClaims struct {
    Foo string `json:"foo"`
    jwt.StandardClaims
}

// sample token is expired.  override time so it parses as valid
tokenClaims, err := jwt.ParseWithClaims(token, &MyCustomClaims{},func(token *jwt.Token) (interface{}, error) {
        return []byte("AllYourBase"), nil
})

if tokenClaims != nil {
    if claims, ok := tokenClaims.Claims.(*MyCustomClaims); ok && tokenClaims.Valid {
        fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
    } else {
        fmt.Println(err)
    }
}

個人實戰

package jwt
...
...


var jwtSecret = []byte("AllYourBase")

type Claims struct {
    Username string `json:"username"`
    Password string `json:"password"`
    jwt.StandardClaims
}

func GenerateToken(username, password string) (string, error) {
    expireAt := time.Now().Add(time.Hour).Unix()

    claims := Claims{
        username,
        password,
        jwt.StandardClaims{
            ExpiresAt: expireAt,
            Issuer: "xxxxxx",
        },
    }

    tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

    token, err := tokenClaims.SignedString(jwtSecret)

    return token, err
}

func ParseToken(token string) (*Claims, error) {
    tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
        return jwtSecret, nil
    })

    if tokenClaims != nil {
        if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
            return claims, nil
        }
    }

    return nil, err
}

生成token

token, err := jwt.GenerateToken(username, password)

解析token

claims, err := jwt.ParseToken(token)
本作品採用《CC 協議》,轉載必須註明作者和本文連結
attitudefx

相關文章