44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
|
|
"git.apinb.com/bsm-sdk/core/crypto/encipher"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func JwtAuth(redisToken string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 从请求头中获取 Authorization
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
log.Println("获取token异常:", "Authorization header is required")
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
// 提取Token
|
|
claims, err := encipher.ParseTokenAes(authHeader)
|
|
if err != nil || claims == nil {
|
|
log.Println("提取token异常:", "Token is required")
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 从redis 获取token,判断当前redis 是否为空
|
|
if redisToken == "" {
|
|
log.Println("redis异常", "Token status unauthorized")
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token status unauthorized"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 将解析后的 Token 存储到上下文中
|
|
c.Set("Auth", claims)
|
|
// 如果 Token 有效,继续处理请求
|
|
c.Next()
|
|
}
|
|
}
|