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

This commit is contained in:
junleea 2025-05-18 14:10:27 +08:00
parent 7d1c8ae493
commit a044f5ec0a
2 changed files with 82 additions and 76 deletions

81
main.go
View File

@ -107,41 +107,32 @@ func JWTAuthMiddleware() gin.HandlerFunc {
} }
// 从请求头中获取 JWT 令牌 // 从请求头中获取 JWT 令牌
tokenString := c.Request.Header.Get("token") tokenString := c.Request.Header.Get("token")
//请求方式为get时从url中获取token //请求方式为get时从url中获取token
if tokenString == "" { if tokenString == "" {
tokenString = c.Query("token") tokenString = c.Query("token")
} }
//如果请求为login或register则不需要验证token //for k, _ := range proto.Url_map {
for k, _ := range proto.Url_map { // if strings.Contains(c.Request.URL.Path, k) {
if strings.Contains(c.Request.URL.Path, k) { // log.Println("need not check token:", c.Request.URL.Path)
log.Println("need not check token:", c.Request.URL.Path) // c.Next()
// return
// }
//}
if proto.Url_map[c.Request.URL.Path] == true { //查看是否在不需要token的url中
c.Next() c.Next()
return return
} }
}
if tokenString == "" { if tokenString == "" {
//c.AbortWithStatus(200) c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "unauthorized", "error": "token is empty", "code": proto.TokenIsNull})
c.JSON(200, gin.H{
"message": "Unauthorized",
"error": "token is empty",
"code": proto.TokenIsNull,
})
return return
} }
if proto.Config.TOKEN_USE_REDIS { if proto.Config.TOKEN_USE_REDIS {
redisToken := worker.GetRedis(tokenString) redisToken := worker.GetRedis(tokenString)
if redisToken == "" { if redisToken == "" {
c.AbortWithStatus(200) c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "NOT_LOGIN", "error": "server token is empty", "code": proto.TokenIsNull})
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "server token is empty",
"code": proto.TokenIsNull,
})
return return
} }
} }
//查看token是否在超级token中 //查看token是否在超级token中
if worker.IsContainSet("super_permission_tokens", tokenString) { if worker.IsContainSet("super_permission_tokens", tokenString) {
sId := c.Request.Header.Get("super_id") sId := c.Request.Header.Get("super_id")
@ -149,12 +140,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
sId = c.Query("super_id") sId = c.Query("super_id")
} }
if sId == "" { if sId == "" {
c.AbortWithStatus(200) c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "unauthorized", "error": "super_id is empty", "code": proto.TokenIsNull})
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "super_id is empty",
"code": proto.TokenIsNull,
})
return return
} }
id, _ := strconv.Atoi(sId) id, _ := strconv.Atoi(sId)
@ -167,20 +153,34 @@ func JWTAuthMiddleware() gin.HandlerFunc {
} }
// 使用加密secret 解析 JWT 令牌 // 使用加密secret 解析 JWT 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { //token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// return proto.SigningKey, nil
//})
claims := &proto.CustomClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
// 验证签名算法
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return proto.SigningKey, nil return proto.SigningKey, nil
}) })
// 错误处理
// 验证令牌 if err != nil {
if err != nil || !token.Valid { if ve, ok := err.(*jwt.ValidationError); ok {
c.AbortWithStatus(200) switch {
c.JSON(200, gin.H{ case ve.Errors&jwt.ValidationErrorMalformed != 0:
"message": "NOT_LOGIN", c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Malformed token", "code": proto.TokenInvalid})
"error": "Invalid token", case ve.Errors&jwt.ValidationErrorExpired != 0:
"code": proto.TokenExpired, c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Token expired", "code": proto.TokenExpired})
}) case ve.Errors&jwt.ValidationErrorNotValidYet != 0:
c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Token not active yet", "code": proto.TokenInvalid})
default:
c.AbortWithStatusJSON(http.StatusOK, gin.H{"error": "Invalid token", "code": proto.TokenInvalid})
}
return return
} }
}
// 将用户信息添加到上下文中 // 将用户信息添加到上下文中
c.Set("id", token.Claims.(jwt.MapClaims)["id"]) c.Set("id", token.Claims.(jwt.MapClaims)["id"])
@ -190,18 +190,11 @@ func JWTAuthMiddleware() gin.HandlerFunc {
c.Set("user_id", userID) c.Set("user_id", userID)
if UserFuncIntercept(int(token.Claims.(jwt.MapClaims)["id"].(float64)), c.Request.URL.Path) { if UserFuncIntercept(int(token.Claims.(jwt.MapClaims)["id"].(float64)), c.Request.URL.Path) {
c.AbortWithStatus(200) c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "unauthorized", "error": "no function permission", "code": proto.NoPermission})
c.JSON(http.StatusOK, gin.H{
"message": "no function permission",
"error": "no permission",
"code": proto.NoPermission,
})
return return
} }
// 继续处理请求 // 继续处理请求
c.Next() c.Next()
//log.Println("JWT token is valid, user ID:", token.Claims.(jwt.MapClaims)["id"], " path:", c.Request.URL.Path) //log.Println("JWT token is valid, user ID:", token.Claims.(jwt.MapClaims)["id"], " path:", c.Request.URL.Path)
} }
} }
@ -365,7 +358,7 @@ func RunGeneralCron() {
// 用户功能拦截,返回true表示拦截false表示不拦截 // 用户功能拦截,返回true表示拦截false表示不拦截
func UserFuncIntercept(id int, url string) bool { func UserFuncIntercept(id int, url string) bool {
//先查看是否有权限 //先查看是否有权限
user := dao.FindUserByUserID(id) user := service.GetUserByIDWithCache(id)
//如果用户有权限,则不拦截 //如果用户有权限,则不拦截
for k, v := range proto.Per_menu_map { for k, v := range proto.Per_menu_map {
if strings.Contains(url, k) { if strings.Contains(url, k) {

View File

@ -3,6 +3,7 @@ package proto
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm" "gorm.io/gorm"
"log" "log"
"os" "os"
@ -174,3 +175,15 @@ func DefaultConfig() {
Config.SERVER_NAME = "default" Config.SERVER_NAME = "default"
Config.SPARK_PPT_USAGE = false Config.SPARK_PPT_USAGE = false
} }
type CustomClaims struct {
ID string `json:"id"`
Username string `json:"username"`
UserID int `json:"user_id"`
jwt.RegisteredClaims
}
func (c CustomClaims) Valid() error {
//TODO implement me
panic("implement me")
}