Webhook签名验证
为了防止不法分子利用webhook对客户进行欺骗攻击,强烈建议使用对Webhook发来的请求进行签名验证,确保安全。
验证Webhook请求的合法性
- 获取request的header里的 "x-goeasy-signature"的value
- 对Request body内容进行签名计算,算法:
- 获取GoEasy secretKey(登录GoEasy控制台,应用详情 -> Appkey -> SecretKey)
- 将secretKey作为秘钥,对request中参数content的值进行sha1加密
- 将加密结果进行Base64编码,结果即为签名
- 计算签名结果与header里的 "x-goeasy-signature"的value相同, 即为合法请求,否则为非法请求
参考代码实现
Java
public String goeasyWebhookSignature(String secretKey, String content){
try {
SecretKeySpec signinKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signinKey);
byte[] rawHmac = mac.doFinal(content.getBytes("UTF8"));
return new BASE64Encoder().encode(rawHmac);
} catch (Exception e) {
log.error("HMACSHA1 failed for key:{} and content:{}", secretKey, content, e);
return null;
}
}
PHP
function getSignature($secretKey, $content) {
return base64_encode(hash_hmac("sha1", $content, $secretKey, true));
}
C#
public string goeasyWebhookSignature(string secretKey,string content)
{
var hmacsha1=new HMACSHA1(Encoding.UTF8.GetBytes(secretKey));
var dataBuffer=Encoding.UTF8.GetBytes(content);
var hashBytes=hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}