jwt token 认证

备注:jwt生成token,无法实现登出,可以考虑redis辅助实现登出

package certificate

import (
    "errors"
    "time"

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

// GenToken 生成token
func GenToken(userName, secretKey string) (string, error) {
    claim := jwt.MapClaims{
        "exp":      time.Now().Add(time.Hour * time.Duration(1)).Unix(),
        "username": userName,
        "nbf":      time.Now().Unix(),
        "iat":      time.Now().Unix(),
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
    tokenStr, err := token.SignedString([]byte(secretKey))
    if err != nil {
        return "", err
    }

    return tokenStr, nil
}

// VerfyToken 验证token
func VerfyToken(token, secretKey string) (string, error) {
    tokenObj, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
        return []byte(secretKey), nil
    })
    if err != nil {
        return "", err
    }

    claims, ok := tokenObj.Claims.(jwt.MapClaims)
    if !ok {
        return "", errors.New("cannot convert claim to mapclaim")
    }

    if !tokenObj.Valid {
        return "", errors.New("token is invalid")
    }

    return claims["username"].(string), nil
}

你可能感兴趣的:(jwt token 认证)