Verify Slack webhooks
Slack signs every Events API request with HMAC-SHA256, so you can confirm it came from Slack and wasn't changed. Recompute the signature over v0:{timestamp}:{raw body} with your app's signing secret, compare it with X-Slack-Signature, and reject a X-Slack-Request-Timestamp more than five minutes from your clock. Slack's Bolt frameworks for JavaScript, Python and Java do this for you. Incoming webhooks, which you send to a channel, have no signature to verify.
These pages cover the Events API, which Slack uses to send events to your app. To post messages into a channel, see incoming webhook limits or how to send external webhooks to Slack.
The facts
v0:{timestamp}:{raw body} The literal v0, the X-Slack-Request-Timestamp value and the request body as sent, joined with colons.
GET or POST: echo the challenge Answer 200 with the challenge value as text/plain.
Slack webhook secret
Each Slack app has one signing secret. It isn't the deprecated verification token, a bot token or the client secret. Keep it in an environment variable, not in source code.
- In your app's settings at api.slack.com/apps: open Basic Information and copy the Signing Secret.
- Use it as a plain UTF-8 string. Slack says there's no need to convert it to binary.
- One per app, so every workspace that installs the app gets events signed with the same secret.
- Rotate it with the Regenerate button next to the Signing Secret. Slack's docs give the old client secret 24 hours but state no overlap for the signing secret, so plan for a cutover.
- Slack's docs describe no test and live split.
Source: Slack docs ↗
Code
// Generated with: slack-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify a Slack Events API request.
*
* Slack signs `v0:{timestamp}:{raw_body}` with HMAC-SHA256 using the app's
* signing secret and sends the result as `X-Slack-Signature: v0=<hex>`.
*
* @param {string} rawBody - Raw request body as UTF-8 string
* @param {string} signatureHeader - X-Slack-Signature header value (e.g. "v0=abc...")
* @param {string} timestampHeader - X-Slack-Request-Timestamp header value (Unix seconds)
* @param {string} signingSecret - Slack App signing secret
* @returns {boolean}
*/
function verifySlackRequest(rawBody, signatureHeader, timestampHeader, signingSecret) {
if (!signatureHeader || !timestampHeader || !signingSecret) {
return false;
}
const timestamp = parseInt(timestampHeader, 10);
if (Number.isNaN(timestamp)) {
return false;
}
// Replay protection: reject requests older than 5 minutes
if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 60 * 5) {
return false;
}
// Slack signs the literal string: "v0:" + timestamp + ":" + raw body
const basestring = `v0:${timestamp}:${rawBody}`;
const expected = 'v0=' + crypto
.createHmac('sha256', signingSecret)
.update(basestring, 'utf8')
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(signatureHeader),
Buffer.from(expected)
);
} catch {
return false;
}
}
// Slack webhook endpoint — must use raw body for signature verification
app.post('/webhooks/slack',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-slack-signature'];
const timestamp = req.headers['x-slack-request-timestamp'];
const rawBody = req.body.toString('utf8');
if (!verifySlackRequest(rawBody, signature, timestamp, process.env.SLACK_SIGNING_SECRET)) {
console.error('Slack signature verification failed');
return res.status(401).send('Invalid signature');
}
let payload;
try {
payload = JSON.parse(rawBody);
} catch {
return res.status(400).send('Invalid JSON');
}
// One-time url_verification challenge when configuring the Request URL
if (payload.type === 'url_verification') {
return res.status(200).json({ challenge: payload.challenge });
}
if (payload.type === 'event_callback') {
const event = payload.event || {};
console.log(`Received ${event.type} (event_id: ${payload.event_id})`);
switch (event.type) {
case 'app_mention':
console.log(`Mentioned by ${event.user} in ${event.channel}: ${event.text}`);
// Your code: Reply via chat.postMessage
break;
case 'message':
console.log(`Message from ${event.user} in ${event.channel}: ${event.text}`);
// Your code: Moderation, logging, automation
break;
case 'reaction_added':
console.log(`Reaction :${event.reaction}: added by ${event.user}`);
// Your code: Approval workflows, polls
break;
case 'reaction_removed':
console.log(`Reaction :${event.reaction}: removed by ${event.user}`);
break;
case 'team_join':
console.log(`New team member joined: ${event.user?.id || event.user}`);
// Your code: Onboarding DM, CRM sync
break;
case 'member_joined_channel':
console.log(`${event.user} joined channel ${event.channel}`);
break;
case 'app_home_opened':
console.log(`App home opened by ${event.user}`);
// Your code: Publish the App Home view
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
}
// Slack requires a 2xx response within 3 seconds, or it will retry
res.status(200).send('OK');
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export for testing
module.exports = { app, verifySlackRequest };
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/slack`);
});
} // Generated with: slack-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify a Slack Events API request.
*
* Slack signs `v0:{timestamp}:{raw_body}` with HMAC-SHA256 using the app's
* signing secret and sends the result as `X-Slack-Signature: v0=<hex>`.
*/
export function verifySlackRequest(
rawBody: string,
signatureHeader: string | null,
timestampHeader: string | null,
signingSecret: string
): boolean {
if (!signatureHeader || !timestampHeader || !signingSecret) {
return false;
}
const timestamp = parseInt(timestampHeader, 10);
if (Number.isNaN(timestamp)) {
return false;
}
// Replay protection: reject requests older than 5 minutes
if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 60 * 5) {
return false;
}
// Slack signs the literal string: "v0:" + timestamp + ":" + raw body
const basestring = `v0:${timestamp}:${rawBody}`;
const expected =
'v0=' +
crypto
.createHmac('sha256', signingSecret)
.update(basestring, 'utf8')
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(signatureHeader),
Buffer.from(expected)
);
} catch {
return false;
}
}
export async function POST(request: NextRequest) {
// Read the raw body — Slack signs the raw bytes, not parsed JSON
const rawBody = await request.text();
const signature = request.headers.get('x-slack-signature');
const timestamp = request.headers.get('x-slack-request-timestamp');
if (!verifySlackRequest(rawBody, signature, timestamp, process.env.SLACK_SIGNING_SECRET!)) {
console.error('Slack signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
let payload: any;
try {
payload = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// One-time url_verification challenge when configuring the Request URL
if (payload.type === 'url_verification') {
return NextResponse.json({ challenge: payload.challenge });
}
if (payload.type === 'event_callback') {
const event = payload.event ?? {};
console.log(`Received ${event.type} (event_id: ${payload.event_id})`);
switch (event.type) {
case 'app_mention':
console.log(`Mentioned by ${event.user} in ${event.channel}: ${event.text}`);
// Your code: Reply via chat.postMessage
break;
case 'message':
console.log(`Message from ${event.user} in ${event.channel}: ${event.text}`);
// Your code: Moderation, logging, automation
break;
case 'reaction_added':
console.log(`Reaction :${event.reaction}: added by ${event.user}`);
// Your code: Approval workflows, polls
break;
case 'reaction_removed':
console.log(`Reaction :${event.reaction}: removed by ${event.user}`);
break;
case 'team_join':
console.log(`New team member joined: ${event.user?.id ?? event.user}`);
// Your code: Onboarding DM, CRM sync
break;
case 'member_joined_channel':
console.log(`${event.user} joined channel ${event.channel}`);
break;
case 'app_home_opened':
console.log(`App home opened by ${event.user}`);
// Your code: Publish the App Home view
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
}
// Slack requires a 2xx response within 3 seconds, or it will retry
return NextResponse.json({ received: true });
} # Generated with: slack-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
import time
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, PlainTextResponse
load_dotenv()
app = FastAPI()
def verify_slack_request(
raw_body: bytes,
signature_header: str | None,
timestamp_header: str | None,
signing_secret: str | None,
) -> bool:
"""Verify an Events API request from Slack.
Slack signs ``v0:{timestamp}:{raw_body}`` with HMAC-SHA256 using the app's
signing secret and sends the result as ``X-Slack-Signature: v0=<hex>``.
"""
if not signature_header or not timestamp_header or not signing_secret:
return False
try:
timestamp = int(timestamp_header)
except ValueError:
return False
# Replay protection: reject requests older than 5 minutes
if abs(time.time() - timestamp) > 60 * 5:
return False
# Slack signs the literal string: "v0:" + timestamp + ":" + raw body
basestring = f"v0:{timestamp}:{raw_body.decode('utf-8')}".encode("utf-8")
expected = "v0=" + hmac.new(
signing_secret.encode("utf-8"),
basestring,
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(expected, signature_header)
@app.post("/webhooks/slack")
async def slack_webhook(request: Request):
raw_body = await request.body()
signature_header = request.headers.get("x-slack-signature")
timestamp_header = request.headers.get("x-slack-request-timestamp")
signing_secret = os.environ.get("SLACK_SIGNING_SECRET")
if not verify_slack_request(raw_body, signature_header, timestamp_header, signing_secret):
return PlainTextResponse("Invalid signature", status_code=401)
try:
payload = json.loads(raw_body)
except json.JSONDecodeError:
return PlainTextResponse("Invalid JSON", status_code=400)
# One-time url_verification challenge when configuring the Request URL
if payload.get("type") == "url_verification":
return JSONResponse({"challenge": payload.get("challenge")})
if payload.get("type") == "event_callback":
event = payload.get("event") or {}
event_type = event.get("type")
print(f"Received {event_type} (event_id: {payload.get('event_id')})")
if event_type == "app_mention":
print(
f"Mentioned by {event.get('user')} in {event.get('channel')}: {event.get('text')}"
)
# Your code: Reply via chat.postMessage
elif event_type == "message":
print(
f"Message from {event.get('user')} in {event.get('channel')}: {event.get('text')}"
)
# Your code: Moderation, logging, automation
elif event_type == "reaction_added":
print(f"Reaction :{event.get('reaction')}: added by {event.get('user')}")
# Your code: Approval workflows, polls
elif event_type == "reaction_removed":
print(f"Reaction :{event.get('reaction')}: removed by {event.get('user')}")
elif event_type == "team_join":
user = event.get("user")
user_id = user.get("id") if isinstance(user, dict) else user
print(f"New team member joined: {user_id}")
# Your code: Onboarding DM, CRM sync
elif event_type == "member_joined_channel":
print(f"{event.get('user')} joined channel {event.get('channel')}")
elif event_type == "app_home_opened":
print(f"App home opened by {event.get('user')}")
# Your code: Publish the App Home view
else:
print(f"Unhandled event type: {event_type}")
# Slack requires a 2xx response within 3 seconds, or it will retry
return PlainTextResponse("OK", status_code=200)
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=3000) Or install the Slack webhooks skill:
npx skills add hookdeck/webhook-skills --skill slack-webhooks
Common failures
Body changed before verification
The signature covers the body exactly as Slack sent it. Verify the raw body before any JSON parser touches it.
Base string in the wrong format
Slack signs v0, the timestamp and the body joined with colons, and prefixes the hex digest with v0=. Leaving out the v0: or the v0= means it never matches.
Wrong secret
Use the Signing Secret from Basic Information, as a plain UTF-8 string. The deprecated verification token and the client secret, which sit next to it, won't verify.
Timestamp check after a queue
Slack's check rejects a timestamp more than five minutes from your clock. Verify when the request arrives, because an event that waited in a queue fails it, and so does a server whose clock has drifted.
Let Event Gateway verify Slack signatures.
Event Gateway verifies the signature on each Slack delivery before it reaches your service, then queues it and retries failures on your schedule.