// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package jwtwrapper import ( "fmt" "time" "github.com/dgrijalva/jwt-go" ) var jwtSecret []byte // SetSecret 传入jwt密钥 // 输入:secret 密钥 func SetSecret(secret string) { jwtSecret = []byte(secret) return } // GenToken 生成token // 输入: // id 有可能是用户id // issuer 发行人名称 // subject 自定义信息,如json数据:{"username": "1@email.com", "password":"123456"} // seconds 过期秒数 // 输出:token或错误 func GenToken(id, issuer, subject string, seconds time.Duration) (string, error) { if len(jwtSecret) == 0 { return "", fmt.Errorf("jwtSecret is empty.") } nowTime := time.Now() expireTime := nowTime.Add(seconds) claims := jwt.StandardClaims{ ExpiresAt: expireTime.Unix(), Id: id, Issuer: issuer, Subject: subject, } tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token, err := tokenClaims.SignedString(jwtSecret) return token, err } // ParseToken 解析token成明文信息 // 输入:token 用户登录后的请求 // 输出:明文结构或错误 func ParseToken(token string) (*jwt.StandardClaims, error) { tokenClaims, err := jwt.ParseWithClaims( token, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { return jwtSecret, nil }, ) if tokenClaims != nil { claims, ok := tokenClaims.Claims.(*jwt.StandardClaims) if !ok { return nil, err } if tokenClaims.Valid { return claims, nil } return claims, err } return nil, err }