美文网首页
jwt token 认证

jwt token 认证

作者: csimonj | 来源:发表于2019-03-28 20:55 被阅读0次

    备注: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 认证

          本文链接:https://www.haomeiwen.com/subject/zyfhbqtx.html