Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc(securing-your-webhooks): add standard JavaScript example #27264

Merged
merged 4 commits into from
Aug 10, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions content/webhooks-and-events/webhooks/securing-your-webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,57 @@ def verify_signature(payload_body, secret_token, signature_header):
raise HTTPException(status_code=403, detail="Request signatures didn't match!")
```

### JavaScript example

For example, you can define the following `verifySignature` function and call it in any JavaScript environment - Node.js, Bun, Deno, etc - when you receive a webhook payload:
skedwards88 marked this conversation as resolved.
Show resolved Hide resolved

```javascript
let encoder = new TextEncoder();

async function verifySignature(secret, header, payload) {
let parts = header.split("=");
let sigHex = parts[1];

let algorithm = { name: "HMAC", hash: { name: 'SHA-256' } };

let keyBytes = encoder.encode(secret);
let extractable = false;
let key = await crypto.subtle.importKey(
"raw",
keyBytes,
algorithm,
extractable,
[ "sign", "verify" ],
);

let sigBytes = hexToBytes(sigHex);
let dataBytes = encoder.encode(payload);
let equal = await crypto.subtle.verify(
algorithm.name,
key,
sigBytes,
dataBytes,
);

return equal;
}

function hexToBytes(hex) {
let len = hex.length / 2;
let bytes = new Uint8Array(len);

let index = 0;
for (let i = 0; i < hex.length; i += 2) {
let c = hex.slice(i, i + 2);
let b = parseInt(c, 16);
bytes[index] = b;
index += 1;
}

return bytes;
}
```

### Typescript example

For example, you can define the following `verify_signature` function and call it when you receive a webhook payload:
Expand Down
Loading