1 Star 0 Fork 0

xlizy/common-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
jwt_util.go 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
xlizy 提交于 2024-10-24 10:20 . 重构
package jwt
import (
"fmt"
"gitee.com/xlizy/common-go/base/common_const"
gJwt "github.com/golang-jwt/jwt/v4"
"time"
)
const (
defaultKey = "EcALispjpvf4JrsucfmNtOGQkSni6kDU08aYLfmRHoCXn6M93Nj3wJMSxv2H3E0TvF85oVnpDKswtuFR1R8UF7rXzRe8SMoZv93XPqZCcM0I8ZpnDLZRCKBbz9NOgpCA"
)
type Payload struct {
IdMask string
Roles []string
Expire string
}
type PayloadClaims struct {
Payload Payload
gJwt.RegisteredClaims
}
func GenJwt(payload Payload, key string) string {
if key == "" {
key = defaultKey
}
if payload.Expire == "" {
payload.Expire = time.Now().Add(24 * time.Hour).Format(common_const.DataFormat)
}
// 创建Token结构体
claims := gJwt.NewWithClaims(gJwt.SigningMethodHS256, PayloadClaims{
Payload: payload,
})
// 调用加密方法,生成Token字符串
signingString, err := claims.SignedString([]byte(key))
if err != nil {
fmt.Println(err.Error())
}
return signingString
}
func GetPayload(signingString, key string) (*Payload, error) {
if key == "" {
key = defaultKey
}
// 根据Token字符串解析成Claims结构体
claims, err := gJwt.ParseWithClaims(signingString, &PayloadClaims{}, func(token *gJwt.Token) (interface{}, error) {
return []byte(key), nil
})
if err != nil {
return nil, err
}
return &claims.Claims.(*PayloadClaims).Payload, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xlizy/common-go.git
git@gitee.com:xlizy/common-go.git
xlizy
common-go
common-go
v0.3.1

搜索帮助