// MakeApiSign CheckApiSign 接口签名校验
func MakeApiSign() gin.HandlerFunc {
return func(c *gin.Context) {
requestSign := c.Request.URL.Query().Get("sign")
if requestSign == "" {
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "sign is required",
Timestamp: time.Now(),
})
c.Abort()
return
}
//测试环境暂时不验签
// if strings.ToLower(requestSign) == "1840fe2e75f984847e26534" && config.Conf.ApiSign.Env == "test" {
if strings.ToLower(requestSign) == "1840fe2e75f984847e26534" {
c.Next()
return
}
nonce := c.Request.URL.Query().Get("nonce")
if nonce == "" {
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "nonce is required",
Timestamp: time.Now(),
})
c.Abort()
return
}
ts := c.Request.URL.Query().Get("ts")
tsexp, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "ts is invalid",
Timestamp: time.Now(),
})
logging.Errorf(c.Request.Context(), "MakeApiSignErr %v", err)
c.Abort()
return
}
// 验证过期时间,允许一定的误差
var AppSecret = config.Conf.ApiSign.Appkey
fmt.Println(tsexp)
var ExpireTimeDuration = int64(config.Conf.ApiSign.ExpireTimeDuration)
timestamp := time.Now().Unix()
diffStamp := timestamp - tsexp
if tsexp > timestamp {
diffStamp = tsexp - timestamp
}
if diffStamp >= ExpireTimeDuration {
timestampStr := strconv.FormatInt(timestamp, 10)
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "request timestamp is expire; timestamp:" + timestampStr,
Timestamp: time.Now(),
})
c.Abort()
return
}
// 验证签名是否一致
signStr := ts + nonce + AppSecret
computeSignReal := util.MD5(signStr) // 根据参数计算的签名
if requestSign != computeSignReal {
if config.Conf.Env == "test" {
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "sign wrong;计算的签名sign: " + computeSignReal,
Timestamp: time.Now(),
})
} else {
c.JSON(http.StatusUnauthorized, resp.Response{
Code: 401,
Data: gin.H{},
Message: "sign wrong",
Timestamp: time.Now(),
})
}
c.Abort()
return
}
c.Next()
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。