xy_sh-20260724181350/xy_sh/internal/middleware/middleware.go

54 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"log"
"github.com/gofiber/fiber/v2"
"xy_sh/pkg/crypto"
)
// SM3Salt 全局SM3盐值由config初始化时注入
var SM3Salt []byte
// SM4Key 全局SM4密钥由config初始化时注入
var SM4Key []byte
// AuthMiddleware 签名验证中间件
// 验证请求头中的 timestamp 和 sign
func AuthMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
timestamp := c.Get("timestamp")
sign := c.Get("sign")
if timestamp == "" || sign == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"code": -1,
"msg": "缺少timestamp或sign请求头",
})
}
// 读取请求体中的 encryptedData
var body struct {
EncryptedData string `json:"encryptedData"`
}
if err := c.BodyParser(&body); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"code": -1,
"msg": "请求体解析失败",
})
}
// 验证签名
if !crypto.VerifySign(timestamp, body.EncryptedData, sign, SM3Salt) {
log.Printf("[中间件] 签名验证失败: timestamp=%s, sign=%s", timestamp, sign)
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"code": -1,
"msg": "签名验证失败",
})
}
log.Printf("[中间件] 签名验证通过: timestamp=%s", timestamp)
return c.Next()
}
}