我们建议您对webhoot推推送请求做签名校验,我们使用HmacSHA256 生成签名
请求webhoot API RequestHeader 可以获取签名字符串
header 'X-Mamba-hmac-sha256'
从Request.body获取JSON字符串,使用店铺密钥进行HmacSHA256计算得出签名,然后与X-Mamba-hmac-sha256签名对比即可
java示例代码
@PostMapping("/webHookCall")
public ResponseEntity<String> webHookCall(HttpServletRequest request) {
// 获取 request body 工具类根据实际情况选择
String body = ServletUtil.getBody(request);
String headerSign = request.getHeader("X-Mamba-hmac-sha256");
if(StrUtil.isBlank(headerSign)) {
// 签名为空直接返回失败
return new ResponseEntity<>("fail", HttpStatus.UNAUTHORIZED);
}
String bodySign = HmacUtil.calculateHmac(body, "您的店铺密钥");
if(!headerSign.equals(bodySign)) {
// 签名校验不通过失败
return new ResponseEntity<>("fail", HttpStatus.UNAUTHORIZED);
}
// 处理 业务
....
return new ResponseEntity<>("success", HttpStatus.OK);
}
package com.mazentop.modules.api;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HmacUtil {
public static final String HMAC_ALGORITHM = "HmacSHA256";
public static String calculateHmac(String message, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
Mac hmac = Mac.getInstance(HMAC_ALGORITHM);
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), HMAC_ALGORITHM);
hmac.init(key);
return Base64.encodeBase64String(hmac.doFinal(message.getBytes()));
}
}
输出结果: nApTwfcD/FqUzo4iuiQOwpZkiz0Du5OcgFHWalXf2EE=