123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package utils
- import (
- "errors"
- beego "github.com/beego/beego/v2/server/web"
- "github.com/golang-jwt/jwt/v4"
- "time"
- )
- type MyClaims struct {
- UserId uint `json:"user_id"`
- UserName string `json:"user_name"`
- jwt.RegisteredClaims
- }
- const TokenExpireDuration = time.Hour * 72
- var Serect string
- func CreateToken(userId uint, userName string) (string, error) {
- Issuer, _ := beego.AppConfig.String("Issuer")
- Serect, _ = beego.AppConfig.String("mySerect")
- claims := MyClaims{
- UserId: userId,
- UserName: userName,
- RegisteredClaims: jwt.RegisteredClaims{
- ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenExpireDuration)),
- Issuer: Issuer,
- },
- }
- var mySerect = []byte(Serect)
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- return token.SignedString(mySerect)
- }
- func ParseToken(tokenStr string) (*MyClaims, error) {
- // 使用全局配置中的密钥对token进行解析。
- var mySecret = []byte(Serect)
- // 尝试解析并验证JWT令牌。
- claims := new(MyClaims)
- token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
- return mySecret, nil
- })
- if err != nil {
- if errors.Is(err, jwt.ErrSignatureInvalid) || errors.Is(err, jwt.ErrInvalidKey) {
- return nil, errors.New("无效的签名或密钥")
- } else if ve, ok := err.(*jwt.ValidationError); ok && ve.Errors&jwt.ValidationErrorExpired != 0 {
- return nil, errors.New("令牌已过期")
- }
- return nil, err
- }
- // 验证令牌是否有效。
- if !token.Valid {
- return nil, errors.New("无效的令牌")
- }
- // 如果令牌有效,则返回解析出的声明信息。
- return claims, nil
- }
|