fix: AppCryptoMiddleware添加请求体解密逻辑,修复AES加密通信登录失败
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/pkg/crypto"
|
||||
@@ -41,9 +44,51 @@ func AppCryptoMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
|
||||
shouldEncrypt := encryptType != crypto.EncryptTypeNone
|
||||
cm := crypto.NewCryptoManager(encryptType, app.EncryptKey)
|
||||
|
||||
// 解密请求体
|
||||
if shouldEncrypt {
|
||||
contentType := c.GetHeader("Content-Type")
|
||||
if contentType != "" {
|
||||
// 先尝试从 X-Encrypted-Data Header 解密
|
||||
encryptedHeader := c.GetHeader("X-Encrypted-Data")
|
||||
if encryptedHeader != "" {
|
||||
decrypted, err := cm.Decrypt(encryptedHeader)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"code": 400, "message": "解密失败: " + err.Error()})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBufferString(decrypted))
|
||||
c.Request.ContentLength = int64(len(decrypted))
|
||||
} else {
|
||||
// 从请求体 JSON 的 data 字段解密
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err == nil && len(body) > 0 {
|
||||
var req map[string]interface{}
|
||||
if json.Unmarshal(body, &req) == nil {
|
||||
if dataStr, ok := req["data"].(string); ok {
|
||||
decrypted, err := cm.Decrypt(dataStr)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"code": 400, "message": "解密失败: " + err.Error()})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBufferString(decrypted))
|
||||
c.Request.ContentLength = int64(len(decrypted))
|
||||
} else {
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
}
|
||||
} else {
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.Set("should_encrypt_response", shouldEncrypt)
|
||||
c.Set("crypto_manager", crypto.NewCryptoManager(encryptType, app.EncryptKey))
|
||||
c.Set("crypto_manager", cm)
|
||||
c.Set("app", &app)
|
||||
|
||||
c.Next()
|
||||
|
||||
Reference in New Issue
Block a user