57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
appConfig "base-framework/configs/app"
|
|
"errors"
|
|
"github.com/golang-jwt/jwt"
|
|
"time"
|
|
)
|
|
|
|
// 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) {
|
|
expireTime := time.Now().Add(appConfig.JWT.Expiry).Unix()
|
|
|
|
claims := CustomClaims{
|
|
OrgID: orgID,
|
|
UserID: userID,
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expireTime,
|
|
IssuedAt: time.Now().Unix(),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
signKey := []byte(appConfig.JWT.Secret)
|
|
return token.SignedString(signKey)
|
|
}
|
|
|
|
// VerifyToken 验证并解析 JWT token
|
|
func VerifyToken(tokenString string) (*CustomClaims, error) {
|
|
signKey := []byte(appConfig.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 signKey, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, errors.New("invalid token")
|
|
}
|