Trouble validating a request
Hi there! I'm trying to validate a Discord HTTP request, but I don't know how to do it (https://discord.com/developers/docs/interactions/receiving-and-responding#security-and-authorization)
Discord Developer Portal
Discord Developer Portal — API Docs for Bots and Developers
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
2 Replies
Hello! Validating a Discord HTTP request is an important step to ensure that the requests your application is handling are indeed coming from Discord. According to the documentation, you can use the
validateRequest
function from the sift
module to validate incoming requests. Here's a step-by-step guide based on the documentation:
1. Import the necessary functions from the sift
module:
2. You'll also need to import the nacl
module to verify the signature provided by Discord:
3. Set up your server with the serve
function and define a handler for the route you want to validate, for example, the root ("/"
) route:
4. In your handler function, use validateRequest
to ensure that the request is a POST request and contains the required headers:
5. After validating the request type and headers, proceed to verify the signature using the verifySignature
function you'll define:
```typescript
async function verifySignature(request: Request): Promise<{ valid: boolean; body: string }> {
const PUBLIC_KEY = Deno.env.get("DISCORD_PUBLIC_KEY")!;
const signature = request.headers.get("X-Signature-Ed25519")!;const timestamp = request.headers.get("X-Signature-Timestamp")!;
const body = await request.text();
const valid = nacl.sign.detached.verify(
new TextEncoder().encode(timestamp + body),
hexToUint8Array(signature),
hexToUint8Array(PUBLIC_KEY),
);
return { valid, body };
}
typescript
function hexToUint8Array(hex: string) {
return new Uint8Array(
hex.match(/.{1,2}/g)!.map((val) => parseInt(val, 16)),
);
}
``
7. Finally, use the
verifySignature` function