Unable to correctly verify Slack requests
Here is a working example of how to verify a Slack request, it also supports slash commands:
Slack bot event example | Run in Fusebit |
---|
import crypto from 'crypto';
import formurlencoded from 'form-urlencoded';
export const validateSlackRequest = (
requestSignature: string,
timestampHeader: string, // Get it from the request header x-slack-request-timestamp
contentType: string, // Get it from the request header content-type
signingSecret: string,
timestamp: string,
body: string,
) => {
let rawBody;
if (contentType?.toLocaleLowerCase() === 'application/x-www-form-urlencoded') {
// Slash commands are sent in this content type
rawBody = formurlencoded(body);
} else {
rawBody = JSON.stringify(body)
.replace(/\//g, '\\/')
.replace(/[\u007f-\uffff]/g, (c) => '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4));
}
const basestring = ['v0', timestampHeader, rawBody].join(':');
const calculatedSignature = 'v0=' + crypto.createHmac('sha256', signingSecret).update(basestring).digest('hex');
const calculatedSignatureBuffer = Buffer.from(calculatedSignature, 'utf8');
const requestSignatureBuffer = Buffer.from(requestSignature, 'utf8');
return crypto.timingSafeEqual(calculatedSignatureBuffer, requestSignatureBuffer);
};