📌  相关文章
📜  golang jwt - Go 编程语言代码示例

📅  最后修改于: 2022-03-11 14:45:01.467000             🧑  作者: Mango

代码示例1
package main

import "fmt"

// example usage
func main() {

 userData := map[string]interface{}{"id": 1, "email": "restuwahyu13@zetmail.com", "github_name": "restuwahyu13"}
  accessToken, err := util.Sign(userData, "JWT_SECRET", 1) // data -> secretkey env name -> expiredAt

 fmt.Println("my accessToken here", accessToken)
}

package util

import (
    "encoding/json"
    "strings"
    "time"

    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "github.com/sirupsen/logrus"
)

// metadata for your jwt
type MetaToken struct {
    ID            int
    Email         string
    ExpiredAt     time.Time
    Authorization bool
}

type AccessToken struct {
    Claims MetaToken
}

func Sign(Data map[string]interface{}, SecrePublicKeyEnvName string, ExpiredAt time.Duration) (string, error) {

    expiredAt := time.Now().Add(time.Duration(time.Second) * ExpiredAt).Unix()

    jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)

    // metadata for your jwt
    claims := jwt.MapClaims{}
    claims["expiredAt"] = expiredAt
    claims["authorization"] = true

    for i, v := range Data {
        claims[i] = v
    }

    to := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    accessToken, err := to.SignedString([]byte(jwtSecretKey))

    if err != nil {
        logrus.Error(err.Error())
        return accessToken, err
    }

    return accessToken, nil
}

func VerifyTokenHeader(ctx *gin.Context, SecrePublicKeyEnvName string) (*jwt.Token, error) {
    tokenHeader := ctx.GetHeader("Authorization")
    accessToken := strings.SplitAfter(tokenHeader, "Bearer")[1]
    jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)

    token, err := jwt.Parse(strings.Trim(accessToken, " "), func(token *jwt.Token) (interface{}, error) {
        return []byte(jwtSecretKey), nil
    })

    if err != nil {
        logrus.Error(err.Error())
        return nil, err
    }

    return token, nil
}

func VerifyToken(accessToken, SecrePublicKeyEnvName string) (*jwt.Token, error) {
    jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)

    token, err := jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
        return []byte(jwtSecretKey), nil
    })

    if err != nil {
        logrus.Error(err.Error())
        return nil, err
    }

    return token, nil
}

func DecodeToken(accessToken *jwt.Token) AccessToken {
    var token AccessToken
    stringify, _ := json.Marshal(&accessToken)
    json.Unmarshal([]byte(stringify), &token)

    return token
}