Verify LinkedIn webhooks
LinkedIn signs each POST with an HMAC-SHA256 keyed with your app's clientSecret, so you can confirm a delivery came from LinkedIn and wasn't changed. The string to sign is the literal hmacsha256= followed by the raw body, and X-LI-Signature holds only the lowercase hex digest. Your URL also has to answer a GET challenge with the same secret, when you register it and about every 2 hours after that.
The facts
hmacsha256={raw body} The literal string hmacsha256=, then the POST body exactly as received, with no timestamp added. The prefix never appears in the header.
GET: sign the challenge HTTP 200 within 3 seconds, with Content-Type: application/json and a JSON body holding challengeCode and challengeResponse, the lowercase hex HMAC-SHA256 of the challengeCode keyed with your clientSecret. After 3 failed re-validations in a row, the endpoint is blocked.
Answer the GET challenge with an HMAC of `challengeCode`, then on each POST recompute an HMAC over `hmacsha256=` plus the raw body and compare LinkedIn webhook secret
LinkedIn signs with your app's clientSecret, the same Client Secret you use for OAuth. There is no separate webhook secret, and it also signs the GET challenge response. Keep it in an environment variable, not in source code.
- In the LinkedIn Developer Portal, under your app. Each application is assigned its own Client ID and Client Secret.
- One per developer application. Parent-child integrations such as Apply Connect use the child application's secret, and the challenge names it with an
applicationIdquery parameter. - LinkedIn's webhook docs describe no webhook-specific secret, no test and live split, and no rotation procedure.
- Lead Sync also lets you add your own token to the webhook URL as a second check, such as
?secret=some-generated-token. That token is yours and signs nothing.
Source: LinkedIn docs ↗
Code
Docs discrepancy · read before the code
The Apply Connect page says to add the hmacsha256= prefix to your computed signature for a complete match. The shared Webhooks page says the header holds only the hex digest, and the sample headers on the Talent pages are bare hex. Follow the shared page, and hash the bytes as received.
// Generated with: linkedin-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Compute the challengeResponse for LinkedIn endpoint validation (GET).
* challengeResponse = hex(HMACSHA256(challengeCode, clientSecret))
*/
function challengeResponse(challengeCode, clientSecret) {
return crypto.createHmac('sha256', clientSecret).update(challengeCode).digest('hex');
}
/**
* Verify a LinkedIn push-event signature (POST).
* X-LI-Signature = hex(HMACSHA256("hmacsha256=" + rawBody, clientSecret))
* The "hmacsha256=" prefix is part of the string-to-sign only, not the header.
* @param {Buffer|string} rawBody - Raw request body (unparsed)
* @param {string} signatureHeader - X-LI-Signature header value (bare hex digest)
* @param {string} clientSecret - App client secret
* @returns {boolean}
*/
function verifyLinkedInWebhook(rawBody, signatureHeader, clientSecret) {
if (!signatureHeader) {
return false;
}
const stringToSign = Buffer.concat([
Buffer.from('hmacsha256='),
Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody),
]);
const expected = crypto
.createHmac('sha256', clientSecret)
.update(stringToSign)
.digest('hex');
// Timing-safe comparison; wrap because it throws on length mismatch.
try {
return crypto.timingSafeEqual(
Buffer.from(signatureHeader, 'hex'),
Buffer.from(expected, 'hex')
);
} catch {
return false;
}
}
/**
* Classify a LinkedIn notification. LinkedIn sends no event-type header, so the
* product is derived from the payload. Adapt the field checks to the products
* your app subscribes to.
*/
function getNotificationType(payload) {
if (payload.eventType) {
return payload.eventType;
}
if ('leadType' in payload || 'leadAction' in payload || 'leadMetadata' in payload) {
return 'LEAD_ACTION';
}
if ('organizationSocialAction' in payload || 'socialAction' in payload) {
return 'ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS';
}
return 'UNKNOWN';
}
// Dedupe store — notifications may be delivered more than once.
// Replace with Redis/DB in production.
const processedNotifications = new Set();
// GET: LinkedIn endpoint validation. Must respond within 3s as JSON.
app.get('/webhooks/linkedin', (req, res) => {
const challengeCode = req.query.challengeCode;
if (!challengeCode) {
return res.status(400).json({ error: 'Missing challengeCode' });
}
res.status(200).json({
challengeCode,
challengeResponse: challengeResponse(challengeCode, process.env.LINKEDIN_CLIENT_SECRET),
});
});
// POST: LinkedIn event delivery. Raw body required for signature verification.
app.post('/webhooks/linkedin',
express.raw({ type: '*/*' }),
(req, res) => {
const signature = req.headers['x-li-signature'];
if (!verifyLinkedInWebhook(req.body, signature, process.env.LINKEDIN_CLIENT_SECRET)) {
console.error('LinkedIn webhook signature verification failed');
return res.status(401).send('Invalid signature');
}
// Parse only after verifying.
const payload = JSON.parse(req.body.toString());
const notificationType = getNotificationType(payload);
// Dedupe on notificationId before processing.
const notificationId = payload.notificationId;
if (notificationId && processedNotifications.has(notificationId)) {
console.log(`Duplicate notification ${notificationId}, skipping`);
return res.status(200).send('OK');
}
if (notificationId) {
processedNotifications.add(notificationId);
}
console.log(`Received ${notificationType} notification (${notificationId})`);
switch (notificationType) {
case 'LEAD_ACTION':
console.log('Lead Sync action:', payload.leadType);
// Your code: fetch full lead via the Lead Sync pull API, enqueue to CRM, etc.
break;
case 'ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS':
console.log('Org social action on:', payload.organizationSocialAction || payload.object);
// Your code: moderate comment, notify community manager, etc.
break;
default:
console.log(`Unhandled notification type: ${notificationType}`);
}
// Acknowledge with a 2xx so LinkedIn does not retry.
res.status(200).send('OK');
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = { app, verifyLinkedInWebhook, challengeResponse, getNotificationType };
// 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: http://localhost:${PORT}/webhooks/linkedin`);
});
} // Generated with: linkedin-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Compute the challengeResponse for LinkedIn endpoint validation (GET).
* challengeResponse = hex(HMACSHA256(challengeCode, clientSecret))
*/
export function challengeResponse(challengeCode: string, clientSecret: string): string {
return crypto.createHmac('sha256', clientSecret).update(challengeCode).digest('hex');
}
/**
* Verify a LinkedIn push-event signature (POST).
* X-LI-Signature = hex(HMACSHA256("hmacsha256=" + rawBody, clientSecret))
* The "hmacsha256=" prefix is part of the string-to-sign only, not the header.
*/
export function verifyLinkedInWebhook(
rawBody: string,
signatureHeader: string | null,
clientSecret: string
): boolean {
if (!signatureHeader) {
return false;
}
const expected = crypto
.createHmac('sha256', clientSecret)
.update('hmacsha256=' + rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(signatureHeader, 'hex'),
Buffer.from(expected, 'hex')
);
} catch {
return false;
}
}
/**
* Classify a LinkedIn notification. LinkedIn sends no event-type header, so the
* product is derived from the payload. Adapt the field checks to the products
* your app subscribes to.
*/
export function getNotificationType(payload: Record<string, unknown>): string {
if (payload.eventType) {
return payload.eventType as string;
}
if ('leadType' in payload || 'leadAction' in payload || 'leadMetadata' in payload) {
return 'LEAD_ACTION';
}
if ('organizationSocialAction' in payload || 'socialAction' in payload) {
return 'ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS';
}
return 'UNKNOWN';
}
// Dedupe store — notifications may be delivered more than once.
// Replace with Redis/DB in production.
const processedNotifications = new Set<string>();
// GET: LinkedIn endpoint validation. Must respond within 3s as JSON.
export async function GET(request: NextRequest) {
const challengeCode = request.nextUrl.searchParams.get('challengeCode');
if (!challengeCode) {
return NextResponse.json({ error: 'Missing challengeCode' }, { status: 400 });
}
return NextResponse.json({
challengeCode,
challengeResponse: challengeResponse(challengeCode, process.env.LINKEDIN_CLIENT_SECRET!),
});
}
// POST: LinkedIn event delivery. Read the raw body for signature verification.
export async function POST(request: NextRequest) {
const rawBody = await request.text();
const signature = request.headers.get('x-li-signature');
if (!verifyLinkedInWebhook(rawBody, signature, process.env.LINKEDIN_CLIENT_SECRET!)) {
console.error('LinkedIn webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
// Parse only after verifying.
const payload = JSON.parse(rawBody);
const notificationType = getNotificationType(payload);
const notificationId: string | undefined = payload.notificationId;
// Dedupe on notificationId before processing.
if (notificationId && processedNotifications.has(notificationId)) {
console.log(`Duplicate notification ${notificationId}, skipping`);
return NextResponse.json({ received: true });
}
if (notificationId) {
processedNotifications.add(notificationId);
}
console.log(`Received ${notificationType} notification (${notificationId})`);
switch (notificationType) {
case 'LEAD_ACTION':
console.log('Lead Sync action:', payload.leadType);
// Your code: fetch full lead via the Lead Sync pull API, enqueue to CRM, etc.
break;
case 'ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS':
console.log('Org social action on:', payload.organizationSocialAction || payload.object);
// Your code: moderate comment, notify community manager, etc.
break;
default:
console.log(`Unhandled notification type: ${notificationType}`);
}
// Acknowledge with a 2xx so LinkedIn does not retry.
return NextResponse.json({ received: true });
} # Generated with: linkedin-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import hmac
import hashlib
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response, HTTPException
load_dotenv()
app = FastAPI()
client_secret = os.environ.get("LINKEDIN_CLIENT_SECRET", "")
def challenge_response(challenge_code: str, secret: str) -> str:
"""Compute the challengeResponse for LinkedIn endpoint validation (GET).
challengeResponse = hex(HMACSHA256(challengeCode, clientSecret))
"""
return hmac.new(secret.encode("utf-8"), challenge_code.encode("utf-8"), hashlib.sha256).hexdigest()
def verify_linkedin_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
"""Verify a LinkedIn push-event signature (POST).
X-LI-Signature = hex(HMACSHA256("hmacsha256=" + rawBody, clientSecret))
The "hmacsha256=" prefix is part of the string-to-sign only, not the header.
"""
if not signature_header:
return False
string_to_sign = b"hmacsha256=" + raw_body
expected = hmac.new(secret.encode("utf-8"), string_to_sign, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature_header, expected)
def get_notification_type(payload: dict) -> str:
"""Classify a LinkedIn notification.
LinkedIn sends no event-type header, so the product is derived from the
payload. Adapt the field checks to the products your app subscribes to.
"""
if payload.get("eventType"):
return payload["eventType"]
if "leadType" in payload or "leadAction" in payload or "leadMetadata" in payload:
return "LEAD_ACTION"
if "organizationSocialAction" in payload or "socialAction" in payload:
return "ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS"
return "UNKNOWN"
# Dedupe store — notifications may be delivered more than once.
# Replace with Redis/DB in production.
processed_notifications: set[str] = set()
@app.get("/webhooks/linkedin")
async def validate_endpoint(request: Request):
"""LinkedIn endpoint validation. Must respond within 3s as JSON."""
challenge_code = request.query_params.get("challengeCode")
if not challenge_code:
raise HTTPException(status_code=400, detail="Missing challengeCode")
return {
"challengeCode": challenge_code,
"challengeResponse": challenge_response(challenge_code, client_secret),
}
@app.post("/webhooks/linkedin")
async def receive_webhook(request: Request):
"""LinkedIn event delivery. Raw body required for signature verification."""
raw_body = await request.body()
signature = request.headers.get("x-li-signature")
if not verify_linkedin_webhook(raw_body, signature, client_secret):
raise HTTPException(status_code=401, detail="Invalid signature")
# Parse only after verifying.
payload = json.loads(raw_body)
notification_type = get_notification_type(payload)
notification_id = payload.get("notificationId")
# Dedupe on notificationId before processing.
if notification_id and notification_id in processed_notifications:
print(f"Duplicate notification {notification_id}, skipping")
return {"received": True}
if notification_id:
processed_notifications.add(notification_id)
print(f"Received {notification_type} notification ({notification_id})")
if notification_type == "LEAD_ACTION":
print(f"Lead Sync action: {payload.get('leadType')}")
# Your code: fetch full lead via the Lead Sync pull API, enqueue to CRM, etc.
elif notification_type == "ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS":
print(f"Org social action on: {payload.get('organizationSocialAction') or payload.get('object')}")
# Your code: moderate comment, notify community manager, etc.
else:
print(f"Unhandled notification type: {notification_type}")
# Acknowledge with a 2xx so LinkedIn does not retry.
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the LinkedIn webhooks skill:
npx skills add hookdeck/webhook-skills --skill linkedin-webhooks
Common failures
Prefix missing from the string to sign
Hashing the body alone gives a different result. Hash hmacsha256= followed by the body.
Prefix added to the comparison
The header holds only the hex digest, so compare your digest with the whole value. LinkedIn's Apply Connect page says to add the prefix to your signature, which disagrees with its shared Webhooks page and with the sample headers on its Talent pages.
Body changed before verification
LinkedIn says to use the body exactly as received. Re-serializing, pretty-printing or reformatting the JSON makes the signature fail.
Another app's secret
Use the clientSecret of the app that owns the webhook. On parent-child integrations such as Apply Connect, the GET challenge names the app with an applicationId query parameter, and its response must use that app's secret.
Let Event Gateway verify LinkedIn signatures.
Event Gateway verifies the signature on each LinkedIn delivery before it reaches your service, then queues it and retries failures on your schedule.