修改jwt拦截处理,添加错误问题

This commit is contained in:
junleea 2025-05-18 14:22:01 +08:00
parent 3aa2f63216
commit 0a02b2e6dd
1 changed files with 18 additions and 4 deletions

22
main.go
View File

@ -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
}
}
// 将用户信息添加到上下文中