This commit is contained in:
oneao committed 2025-08-12 21:47:37 +08:00
1 parent 9af3234672
commit ed8bee3d77
11 files changed
+171 -57

No files matched your search

+22 -10
View File
@@ -1,22 +1,28 @@
package utils
import (
appConfig "base-framework/configs/app"
commonConfig "base-framework/pkg/config"
"errors"
"github.com/golang-jwt/jwt"
"time"
"github.com/golang-jwt/jwt"
)
// CustomClaims 定义自己的 payload 结构,可以根据需要扩展
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
// CreateToken 创建一个 JWT token
func CreateToken(orgID, userID string) (string, error) {
expireTime := time.Now().Add(appConfig.JWT.Expiry).Unix()
expireTime := time.Now().Add(commonConfig.JWT.Expiry).Unix()
claims := CustomClaims{
OrgID: orgID,
@@ -28,29 +34,35 @@ func CreateToken(orgID, userID string) (string, error) {
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signKey := []byte(appConfig.JWT.Secret)
signKey := []byte(commonConfig.JWT.Secret)
return token.SignedString(signKey)
}
// VerifyToken 验证并解析 JWT token
func VerifyToken(tokenString string) (*CustomClaims, error) {
signKey := []byte(appConfig.JWT.Secret)
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, errors.New("unexpected signing method")
return nil, ErrTokenInvalid
}
return signKey, nil
})
if err != nil {
return nil, err
// 判断是否过期错误
if ve, ok := err.(*jwt.ValidationError); ok {
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, errors.New("invalid token")
return nil, ErrTokenInvalid
}