1 Star 0 Fork 0

GarlicBoris/gozero-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
token.go 2.15 KB
一键复制 编辑 原始数据 按行查看 历史
yanwc 提交于 2024-05-25 22:27 . feat: token
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
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yanwc/gozero-utils.git
git@gitee.com:yanwc/gozero-utils.git
yanwc
gozero-utils
gozero-utils
v1.2.61

搜索帮助