u
This commit is contained in:
1 parent
7c8e2906bc
commit
72a1a9184a
25 files changed
+744
-125
No files matched your search
@@ -0,0 +1,57 @@
|
||||
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(),
|
||||
Issuer: "your-app-name", // 可以自定义
|
||||
},
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
Reference in new issue
Block a user