代码拉取完成,页面将自动刷新
package jwtx
import (
"encoding/json"
"errors"
"time"
jwt "github.com/golang-jwt/jwt/v5"
)
type TokenOption struct {
Exp *jwt.NumericDate
Sub string
Aud string
Iss string
}
const (
defaultExpDurationSeconds = 60 * 60 * 8
)
type Option func(*TokenOption)
func NewToken(data any, key string, opts ...Option) (string, error) {
cfg := TokenOption{
Exp: &jwt.NumericDate{Time: time.Now().Add(time.Second * time.Duration(defaultExpDurationSeconds))},
Sub: "uhk-system",
Iss: "uhk",
Aud: "uhk",
}
for _, o := range opts {
o(&cfg)
}
jsonString, err := json.Marshal(data)
if err != nil {
return "", err
}
claims := jwt.MapClaims{
"data": string(jsonString),
"exp": cfg.Exp,
"iss": cfg.Iss,
"sub": cfg.Sub,
"aud": cfg.Aud,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(key))
}
func NewTokenWithExp(data any, key string) (string, error) {
return NewToken(data, key)
}
func ParseToken[T any](tokenString string, secret string, target *T) error {
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return err
}
if !token.Valid {
return errors.New("token 验证失败")
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
t := claims["data"]
if v, ok := t.(string); ok {
err = json.Unmarshal([]byte(v), target)
if err != nil {
return err
}
}
return nil
} else {
return nil
}
}
func Valid(tokenString string, secret string) (bool, error) {
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return false, err
}
return token.Valid, nil
}
func WithSubOption(sub string) Option {
return func(to *TokenOption) {
to.Sub = sub
}
}
func WithIssOption(iss string) Option {
return func(to *TokenOption) {
to.Iss = iss
}
}
func WithExpOption(expDurationSeconds int64) Option {
return func(to *TokenOption) {
to.Exp = &jwt.NumericDate{Time: time.Now().Add(time.Second * time.Duration(expDurationSeconds))}
}
}
func WithAudOption(aud string) Option {
return func(to *TokenOption) {
to.Aud = aud
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。