From 0a02b2e6dda83dde9b1494d67f78fd080106aa04 Mon Sep 17 00:00:00 2001 From: junleea <354425203@qq.com> Date: Sun, 18 May 2025 14:22:01 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9jwt=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E5=A4=84=E7=90=86=EF=BC=8C=E6=B7=BB=E5=8A=A0=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index d60e74a..bf10c5c 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "StuAcaWorksAI/service" "StuAcaWorksAI/worker" "encoding/json" + "errors" "fmt" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt" @@ -101,9 +102,9 @@ func writeLogger(c *gin.Context) { } type CustomClaims struct { - ID string `json:"id"` + ID int `json:"id"` Username string `json:"username"` - UserID int `json:"user_id"` + Email string `json:"email"` } func (c CustomClaims) Valid() error { @@ -177,8 +178,21 @@ func JWTAuthMiddleware() gin.HandlerFunc { return proto.SigningKey, nil }) // 错误处理 - if err != nil || token.Valid == false { - c.AbortWithStatusJSON(http.StatusOK, gin.H{"code": proto.TokenInvalid, "message": "unauthorized", "error": "token is invalid:" + err.Error()}) + if err != nil { + var ve *jwt.ValidationError + if errors.As(err, &ve) { + switch { + case ve.Errors&jwt.ValidationErrorMalformed != 0: + c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Malformed token:" + err.Error(), "code": proto.TokenInvalid}) + case ve.Errors&jwt.ValidationErrorExpired != 0: + c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Token expired:" + err.Error(), "code": proto.TokenExpired}) + case ve.Errors&jwt.ValidationErrorNotValidYet != 0: + c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Token not active yet:" + err.Error(), "code": proto.TokenInvalid}) + default: + c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Invalid token:" + err.Error(), "code": proto.TokenInvalid}) + } + return + } } // 将用户信息添加到上下文中