2024-09-29 16:55:00 +08:00

45 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"github.com/golang-jwt/jwt/v5"
"knowledge/config"
"time"
)
type Token struct {
UserId string `json:"user_id"` // 用户id
Client int `json:"client"` // 客户端1:前台 2:后台)
QaId string `json:"qa_id"` // 知识问答id
jwt.RegisteredClaims // v5版本新加的方法
}
// NewJWT GenerateJWT 生成JWT
func (t Token) NewJWT(ttl time.Duration) (string, error) {
if ttl == 0 {
ttl = time.Duration(config.C.Jwt.Ttl)
}
t.RegisteredClaims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(ttl * time.Hour)) // 过期时间24小时
t.RegisteredClaims.IssuedAt = jwt.NewNumericDate(time.Now()) // 签发时间
t.RegisteredClaims.NotBefore = jwt.NewNumericDate(time.Now()) // 生效时间
// 使用HS256签名算法
token := jwt.NewWithClaims(jwt.SigningMethodHS256, t)
s, err := token.SignedString([]byte(config.C.Jwt.SignKey))
return s, err
}
// ParseJwt 解析JWT
func ParseJwt(authorization string) (*Token, error) {
t, err := jwt.ParseWithClaims(authorization, &Token{}, func(token *jwt.Token) (interface{}, error) {
return []byte(config.C.Jwt.SignKey), nil
})
if claims, ok := t.Claims.(*Token); ok && t.Valid {
return claims, nil
} else {
return nil, err
}
}