package jwt import ( "errors" "github.com/golang-jwt/jwt/v4" jwt2 "matrix-middle-service/pkg/config/jwt" "time" ) var JwtConfig *jwt2.Config // UserClaims // @Param id body string true // @Param account body string true type UserClaims struct { Id string `json:"id"` Account string `json:"account"` Identify string `json:"identify"` jwt.RegisteredClaims `swaggerignore:"true"` } func GetToken(claims UserClaims) (string, error) { iat := time.Now().Unix() claims.IssuedAt = jwt.NewNumericDate(time.Unix(iat, 0)) expire := iat + JwtConfig.Expire claims.ExpiresAt = jwt.NewNumericDate(time.Unix(expire, 0)) token := jwt.New(jwt.SigningMethodHS256) token.Claims = claims return token.SignedString([]byte(JwtConfig.Secret)) } func ParseToken(tokenStr string) (*UserClaims, error) { token, err := jwt.ParseWithClaims(tokenStr, &UserClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(JwtConfig.Secret), nil }) if err != nil { return nil, err } if claims, ok := token.Claims.(*UserClaims); ok && token.Valid { return claims, nil } return nil, errors.New("无效的令牌") }