You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.6 KiB
Go
53 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"gold-shop/global"
|
|
"time"
|
|
)
|
|
|
|
type MyClaims struct {
|
|
Identity int `json:"identity"`
|
|
Role string `json:"role"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GenerateToken(identity int, role string) (string, error) {
|
|
SetClaims := MyClaims{
|
|
Identity: identity,
|
|
Role: role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(3 * time.Hour)), // 有效时间
|
|
IssuedAt: jwt.NewNumericDate(time.Now()), // 签发时间
|
|
NotBefore: jwt.NewNumericDate(time.Now()), // 生效时间
|
|
Issuer: global.Config.Jwt.Issuer, // 签发人
|
|
Subject: "somebody", // 主题
|
|
ID: "1", // JWT ID用于标识该JWT
|
|
Audience: []string{"somebody_else"}, // 用户
|
|
},
|
|
}
|
|
|
|
// 使用指定的加密方式和声明类型创建新令牌
|
|
tokenStruct := jwt.NewWithClaims(jwt.SigningMethodHS256, SetClaims)
|
|
// 获得完整的、签名的令牌
|
|
token, err := tokenStruct.SignedString([]byte(global.Config.Jwt.Key))
|
|
return token, err
|
|
}
|
|
|
|
func CheckToken(token string) (*MyClaims, bool) {
|
|
//解析、验证并返回token。
|
|
tokenObj, err := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(global.Config.Jwt.Key), nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
|
|
if claims, ok := tokenObj.Claims.(*MyClaims); ok && tokenObj.Valid {
|
|
return claims, true
|
|
} else {
|
|
return nil, false
|
|
}
|
|
}
|