标签 jwt 下的文章

golang jwt鉴权


package model

import (
    "fmt"
    "time"

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

const (
    KEY                    string = "JWT-ARY-STARK"
    DEFAULT_EXPIRE_SECONDS int    = 100000 // default 10 minutes
)

// JWT -- json web token
// HEADER PAYLOAD SIGNATURE
// This struct is the PAYLOAD
type MyCustomClaims struct {
    LpUser
    jwt.StandardClaims
}

// update expireAt and return a new token更新expireAt并返回新令牌
func RefreshToken(tokenString string) (string, error) {
    // first get previous token
    token, err := jwt.ParseWithClaims(
        tokenString,
        &MyCustomClaims{},
        func(token *jwt.Token) (interface{}, error) {
            return []byte(KEY), nil
        })
    claims, ok := token.Claims.(*MyCustomClaims)
    if !ok || !token.Valid {
        return "", err
    }
    mySigningKey := []byte(KEY)
    expireAt := time.Now().Add(time.Second * time.Duration(DEFAULT_EXPIRE_SECONDS)).Unix()
    newClaims := MyCustomClaims{
        claims.LpUser,
        jwt.StandardClaims{
            ExpiresAt: expireAt,
            Issuer:    claims.LpUser.Email,
            IssuedAt:  time.Now().Unix(),
        },
    }
    // generate new token with new claims生成带有新声明的新令牌
    newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, newClaims)
    tokenStr, err := newToken.SignedString(mySigningKey)
    if err != nil {
        fmt.Println("generate new fresh json web token failed !! error :", err)
        return "", err
    }
    return tokenStr, err
}

//验证令牌
func ValidateToken(tokenString string) error {
    token, err := jwt.ParseWithClaims(
        tokenString,
        &MyCustomClaims{},
        func(token *jwt.Token) (interface{}, error) {
            return []byte(KEY), nil
        })
    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
        fmt.Printf("%v %v", claims.LpUser, claims.StandardClaims.ExpiresAt)
        fmt.Println("token will be expired at ", time.Unix(claims.StandardClaims.ExpiresAt, 0))
    } else {
        fmt.Println("validate tokenString failed !!!", err)
        return err
    }
    return nil
}

//生成令牌
func GenerateToken(user LpUser, expiredSeconds int) (tokenString string) {
    if expiredSeconds == 0 {
        expiredSeconds = DEFAULT_EXPIRE_SECONDS
    }
    // Create the Claims
    mySigningKey := []byte(KEY)
    expireAt := time.Now().Add(time.Second * time.Duration(expiredSeconds)).Unix()
    fmt.Println("token will be expired at ", time.Unix(expireAt, 0))
    // pass parameter to this func or not
    claims := MyCustomClaims{
        user,
        jwt.StandardClaims{
            ExpiresAt: expireAt,
            Issuer:    user.Name,
            IssuedAt:  time.Now().Unix(),
        },
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenStr, err := token.SignedString(mySigningKey)
    if err != nil {
        fmt.Println("generate json web token failed !! error :", err)
    }
    return tokenStr

}

//解析token
func ParsingToken(tokenString string) (*MyCustomClaims, error) {
    token, err := jwt.ParseWithClaims(
        tokenString,
        &MyCustomClaims{},
        func(token *jwt.Token) (interface{}, error) {
            return []byte(KEY), nil
        })
    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
        fmt.Printf("%v %v", claims.LpUser, claims.StandardClaims.ExpiresAt)
        fmt.Println("token will be expired at ", time.Unix(claims.StandardClaims.ExpiresAt, 0))
        return claims, nil
    } else {
        fmt.Println("validate tokenString failed !!!", err)
        return nil, err
    }
}