I am new to SendGrid, I am able to send email using it using Spring Boot, a sample webhook without any security is also working. now I want to verify the security of the API, i am using ecdsa verification, but every time it gives false when ever I verify. I googled a lot but couldn't find a working program.
@PostMapping("webhook")
public void webhookVerify(@RequestBody List<Webhook> webhook, @RequestHeader Map<String, String> headers) throws Exception {
System.out.println(verify(sendGridVerificationKey, webhook, headers.get("x-twilio-email-event-webhook-signature"), headers.get("x-twilio-email-event-webhook-timestamp"));
}
private boolean verify(final String publicKey, List<Webhook> webhook, final String signature, final String timestamp) throws Exception {
final EventWebhook ew = new EventWebhook();
final ECPublicKey ellipticCurvePublicKey = ew.ConvertPublicKeyToECDSA(publicKey);
return ew.VerifySignature(ellipticCurvePublicKey, payload, signature, timestamp);
}
any one able to verify the same?
CodePudding user response:
I have struggled with the same issue a lot but eventually was able to verify the signature.
SendGrid V3 docs are not very useful in this case.
the key is to use Security.addProvider(new BouncyCastleProvider());
at the time of application startup, and your payload should be in the byte format and don't try to change or convert it.
here is a working solution that helped me.
@PostMapping("webhook")
public void webhook(@RequestBody byte[] webhook, @RequestHeader Map<String, String> headers) throws Exception {
String signature = headers.get("x-twilio-email-event-webhook-signature");
String timeStamp = headers.get("x-twilio-email-event-webhook-timestamp");
if (verify(sendGridVerificationKey, webhook, signature, timeStamp)) {
String str = new String(webhook, StandardCharsets.UTF_8);
System.out.println("ECDSA signature verification true, Webhook = " str);
} else {
throw new InvalidSignatureValueException("ECDSA signature doesn't match");
}
}