71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package jwt
|
|
|
|
import (
|
|
commonConfig "base-framework/pkg/config"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
)
|
|
|
|
var (
|
|
ErrTokenExpired = errors.New("token expired")
|
|
ErrTokenInvalid = errors.New("token invalid")
|
|
)
|
|
|
|
// CustomClaims 定义自己的 payload 结构
|
|
type CustomClaims struct {
|
|
OrgID string `json:"org_id"`
|
|
UserID string `json:"user_id"`
|
|
jwt.StandardClaims
|
|
}
|
|
|
|
// CreateToken 创建一个 JWT token
|
|
func CreateToken(orgID, userID string) (string, error) {
|
|
expireAt := time.Now().Add(commonConfig.JWT.Expiry)
|
|
fmt.Println("Token 过期时间:", expireAt.Format(time.RFC3339))
|
|
|
|
claims := CustomClaims{
|
|
OrgID: orgID,
|
|
UserID: userID,
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expireAt.Unix(),
|
|
IssuedAt: time.Now().Unix(),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(commonConfig.JWT.Secret))
|
|
}
|
|
|
|
// VerifyToken 验证并解析 JWT token
|
|
func VerifyToken(tokenString string) (*CustomClaims, error) {
|
|
signKey := []byte(commonConfig.JWT.Secret)
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
// 校验签名算法
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, ErrTokenInvalid
|
|
}
|
|
return signKey, nil
|
|
})
|
|
|
|
if err != nil {
|
|
// 判断是否过期错误
|
|
var ve *jwt.ValidationError
|
|
if errors.As(err, &ve) {
|
|
if ve.Errors&jwt.ValidationErrorExpired != 0 {
|
|
return nil, ErrTokenExpired
|
|
}
|
|
}
|
|
return nil, ErrTokenInvalid
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, ErrTokenInvalid
|
|
}
|