修改jwt拦截处理,添加错误问题
This commit is contained in:
parent
3aa2f63216
commit
0a02b2e6dd
22
main.go
22
main.go
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"StuAcaWorksAI/service"
|
"StuAcaWorksAI/service"
|
||||||
"StuAcaWorksAI/worker"
|
"StuAcaWorksAI/worker"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt"
|
"github.com/golang-jwt/jwt"
|
||||||
|
|
@ -101,9 +102,9 @@ func writeLogger(c *gin.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
type CustomClaims struct {
|
type CustomClaims struct {
|
||||||
ID string `json:"id"`
|
ID int `json:"id"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
UserID int `json:"user_id"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c CustomClaims) Valid() error {
|
func (c CustomClaims) Valid() error {
|
||||||
|
|
@ -177,8 +178,21 @@ func JWTAuthMiddleware() gin.HandlerFunc {
|
||||||
return proto.SigningKey, nil
|
return proto.SigningKey, nil
|
||||||
})
|
})
|
||||||
// 错误处理
|
// 错误处理
|
||||||
if err != nil || token.Valid == false {
|
if err != nil {
|
||||||
c.AbortWithStatusJSON(http.StatusOK, gin.H{"code": proto.TokenInvalid, "message": "unauthorized", "error": "token is invalid:" + err.Error()})
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 将用户信息添加到上下文中
|
// 将用户信息添加到上下文中
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue