u
This commit is contained in:
1 parent
c7a1f83c67
commit
6849579652
19 files changed
+600
-249
No files matched your search
@@ -0,0 +1,82 @@
|
||||
package jwtx
|
||||
|
||||
import (
|
||||
"base-go-v2/internal/config"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// CustomClaims 自定义 payload,可扩展其他信息
|
||||
type CustomClaims struct {
|
||||
UserID int `json:"user_id"` // 改为 int
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// TokenResult 用于返回验证结果
|
||||
type TokenResult struct {
|
||||
Claims *CustomClaims
|
||||
Valid bool
|
||||
Expired bool
|
||||
}
|
||||
|
||||
// CreateAccessToken 创建 Access Token,只返回 token 和 error
|
||||
func CreateAccessToken(userID int) (string, error) {
|
||||
return createToken(userID, config.App.JWT.AccessExpiry)
|
||||
}
|
||||
|
||||
// CreateRefreshToken 创建 Refresh Token,只返回 token 和 error
|
||||
func CreateRefreshToken(userID int) (string, error) {
|
||||
return createToken(userID, config.App.JWT.RefreshExpiry)
|
||||
}
|
||||
|
||||
// 内部方法,根据过期时间生成 token
|
||||
func createToken(userID int, expiry time.Duration) (string, error) {
|
||||
claims := &CustomClaims{
|
||||
UserID: userID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
switch {
|
||||
case expiry > 0:
|
||||
expireAt := time.Now().Add(expiry)
|
||||
claims.ExpiresAt = jwt.NewNumericDate(expireAt)
|
||||
case expiry == -1:
|
||||
claims.ExpiresAt = nil // 永不过期
|
||||
default:
|
||||
expireAt := time.Now().Add(time.Hour)
|
||||
claims.ExpiresAt = jwt.NewNumericDate(expireAt)
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := token.SignedString([]byte(config.App.JWT.Secret))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return signed, nil
|
||||
}
|
||||
|
||||
// VerifyToken 验证 token 并返回结构化结果
|
||||
func VerifyToken(tokenString string) TokenResult {
|
||||
result := TokenResult{Valid: false}
|
||||
|
||||
token, _ := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(config.App.JWT.Secret), nil
|
||||
})
|
||||
|
||||
claims, ok := token.Claims.(*CustomClaims)
|
||||
if !ok || !token.Valid {
|
||||
return result // token 无效
|
||||
}
|
||||
|
||||
result.Claims = claims
|
||||
result.Valid = true
|
||||
if claims.ExpiresAt != nil && time.Now().After(claims.ExpiresAt.Time) {
|
||||
result.Expired = true
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in new issue
Block a user