Skip to content

Commit 5daea0e

Browse files
authored
Merge pull request #40544 from github/repo-sync
Repo sync
2 parents 2e0e81b + 95ec665 commit 5daea0e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

content/webhooks-and-events/webhooks/securing-your-webhooks.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,57 @@ def verify_signature(payload_body, secret_token, signature_header):
112112
raise HTTPException(status_code=403, detail="Request signatures didn't match!")
113113
```
114114

115+
### JavaScript example
116+
117+
For example, you can define the following `verifySignature` function and call it in any JavaScript environment when you receive a webhook payload:
118+
119+
```javascript
120+
let encoder = new TextEncoder();
121+
122+
async function verifySignature(secret, header, payload) {
123+
let parts = header.split("=");
124+
let sigHex = parts[1];
125+
126+
let algorithm = { name: "HMAC", hash: { name: 'SHA-256' } };
127+
128+
let keyBytes = encoder.encode(secret);
129+
let extractable = false;
130+
let key = await crypto.subtle.importKey(
131+
"raw",
132+
keyBytes,
133+
algorithm,
134+
extractable,
135+
[ "sign", "verify" ],
136+
);
137+
138+
let sigBytes = hexToBytes(sigHex);
139+
let dataBytes = encoder.encode(payload);
140+
let equal = await crypto.subtle.verify(
141+
algorithm.name,
142+
key,
143+
sigBytes,
144+
dataBytes,
145+
);
146+
147+
return equal;
148+
}
149+
150+
function hexToBytes(hex) {
151+
let len = hex.length / 2;
152+
let bytes = new Uint8Array(len);
153+
154+
let index = 0;
155+
for (let i = 0; i < hex.length; i += 2) {
156+
let c = hex.slice(i, i + 2);
157+
let b = parseInt(c, 16);
158+
bytes[index] = b;
159+
index += 1;
160+
}
161+
162+
return bytes;
163+
}
164+
```
165+
115166
### Typescript example
116167

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

0 commit comments

Comments
 (0)