Verify Jira webhooks

Jira signs an admin webhook only if it has a secret, so you can confirm a delivery came from your Jira site and wasn't changed. X-Hub-Signature then holds sha256= followed by an HMAC-SHA256 hex digest of the body, keyed with that secret, on Jira Cloud and in Data Center's docs from 11.0. App webhooks work differently: Connect descriptor and OAuth 2.0 webhooks carry a JWT in Authorization, so this code doesn't apply to them.

These pages cover the events Jira sends from admin and app webhooks. Jira Automation is a separate feature: a rule calls out with its Send web request action and takes calls in with its incoming webhook trigger.

The facts

Signature header
X-Hub-Signature

Not every delivery is signed: check your setup.

Scheme
HMAC-SHA256
Signed material
{raw body}

The request body as you received it. Atlassian says the HMAC uses the payload contents and the payload should be handled as UTF-8, and it mixes in no timestamp or nonce.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Jira webhook secret

Each admin webhook has its own optional secret, which you choose or generate when you create or edit it. App webhooks don't use it: they're secured with your app's client secret or sharedSecret. Keep it in an environment variable, not in source code.

  • Set it on an admin webhook in Jira administration under WebHooks, where Generate secret makes one for you, or pass secret to /rest/webhooks/1.0/webhook.
  • It can't be viewed or retrieved once the webhook is saved, so store it first. If you lose it, set a new one.
  • Rotate it by editing the webhook, then update anything that uses the old value. An imported webhook with a secret may not deliver until you rotate it.
  • With no secret Jira sends no X-Hub-Signature. A REST response shows isSigned: true only when a secret is defined.
  • OAuth 2.0 app webhooks carry a JWT in Authorization, signed with the app's client secret. Connect descriptor webhooks are signed with the app's sharedSecret. The docs don't say how dynamically registered Connect webhooks are authenticated.
  • Data Center's docs from 11.0 describe the same header with a secret set on the webhook, and also offer basic authentication. The 10.7 and earlier pages we checked don't mention a secret.
  • Atlassian's docs describe no test and live split.

Source: Jira docs ↗

Code

express/src/index.js
javascript
// Generated with: jira-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify Jira webhook signature.
 *
 * Jira Cloud signs the raw body with HMAC-SHA256 keyed on the webhook secret and
 * sends it in the X-Hub-Signature header as `sha256=<hex>` (WebSub format).
 *
 * @param {Buffer} rawBody - Raw request body
 * @param {string} signatureHeader - X-Hub-Signature header value (`sha256=<hex>`)
 * @param {string} secret - Jira webhook secret
 * @returns {boolean} - Whether the signature is valid
 */
function verifyJiraWebhook(rawBody, signatureHeader, secret) {
  // Split the WebSub `method=signature` header (e.g. `sha256=<hex>`)
  const [method, sig] = (signatureHeader || '').split('=');
  if (method !== 'sha256' || !sig) {
    return false;
  }

  // Compute the expected signature over the raw body
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // Timing-safe comparison; guards against buffer length mismatch
  try {
    return crypto.timingSafeEqual(
      Buffer.from(sig, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    return false;
  }
}

// Jira webhook endpoint - must use the raw body for signature verification
app.post('/webhooks/jira',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature = req.headers['x-hub-signature'];
    const deliveryId = req.headers['x-atlassian-webhook-identifier'];

    // Verify webhook signature before doing anything else
    if (!verifyJiraWebhook(req.body, signature, process.env.JIRA_WEBHOOK_SECRET)) {
      console.error('Webhook signature verification failed');
      return res.status(401).send('Invalid signature');
    }

    // Parse the payload after verification. Jira has no event-type header —
    // the event name is in the `webhookEvent` field of the body.
    const payload = JSON.parse(req.body.toString());
    const event = payload.webhookEvent;
    const issue = payload.issue;

    console.log(`Received ${event} event (delivery: ${deliveryId})`);

    // Handle the event based on its `webhookEvent` type
    switch (event) {
      case 'jira:issue_created':
        console.log(`Issue created ${issue.key}: ${issue.fields.summary}`);
        // Your code: Sync to external system, auto-assign, notify, etc.
        break;

      case 'jira:issue_updated':
        console.log(`Issue updated ${issue.key}:`, payload.changelog?.items);
        // Your code: Track status changes, trigger automations, etc.
        break;

      case 'jira:issue_deleted':
        console.log(`Issue deleted ${issue.key}`);
        // Your code: Clean up mirrored records, etc.
        break;

      case 'comment_created':
        console.log(`Comment on ${issue.key} by ${payload.comment.author.displayName}`);
        // Your code: ChatOps, notifications, command parsing, etc.
        break;

      case 'comment_updated':
        console.log(`Comment updated on ${issue.key}`);
        // Your code: Audit trails, re-processing, etc.
        break;

      case 'comment_deleted':
        console.log(`Comment deleted on ${issue.key}`);
        // Your code: Audit trails, etc.
        break;

      case 'worklog_created':
        console.log(`Worklog logged on ${issue.key}`);
        // Your code: Time-tracking, billing integrations, etc.
        break;

      default:
        console.log(`Unhandled event: ${event}`);
    }

    // Return 200 to acknowledge receipt
    res.status(200).send('OK');
  }
);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Export app for testing
module.exports = { app, verifyJiraWebhook };

// 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/jira`);
  });
}
nextjs/app/webhooks/jira/route.ts
typescript
// Generated with: jira-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

/**
 * Verify Jira webhook signature.
 *
 * Jira Cloud signs the raw body with HMAC-SHA256 keyed on the webhook secret and
 * sends it in the X-Hub-Signature header as `sha256=<hex>` (WebSub format).
 */
export function verifyJiraWebhook(rawBody: string, signatureHeader: string | null, secret: string): boolean {
  // Split the WebSub `method=signature` header (e.g. `sha256=<hex>`)
  const [method, sig] = (signatureHeader || '').split('=');
  if (method !== 'sha256' || !sig) {
    return false;
  }

  // Compute the expected signature over the raw body
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // Timing-safe comparison; guards against buffer length mismatch
  try {
    return crypto.timingSafeEqual(
      Buffer.from(sig, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  // Get the raw body for signature verification (do not parse before verifying)
  const body = await request.text();
  const signature = request.headers.get('x-hub-signature');
  const deliveryId = request.headers.get('x-atlassian-webhook-identifier');

  // Verify webhook signature before doing anything else
  if (!verifyJiraWebhook(body, signature, process.env.JIRA_WEBHOOK_SECRET!)) {
    console.error('Webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  // Parse the payload after verification. Jira has no event-type header —
  // the event name is in the `webhookEvent` field of the body.
  const payload = JSON.parse(body);
  const event = payload.webhookEvent;
  const issue = payload.issue;

  console.log(`Received ${event} event (delivery: ${deliveryId})`);

  // Handle the event based on its `webhookEvent` type
  switch (event) {
    case 'jira:issue_created':
      console.log(`Issue created ${issue.key}: ${issue.fields.summary}`);
      // Your code: Sync to external system, auto-assign, notify, etc.
      break;

    case 'jira:issue_updated':
      console.log(`Issue updated ${issue.key}:`, payload.changelog?.items);
      // Your code: Track status changes, trigger automations, etc.
      break;

    case 'jira:issue_deleted':
      console.log(`Issue deleted ${issue.key}`);
      // Your code: Clean up mirrored records, etc.
      break;

    case 'comment_created':
      console.log(`Comment on ${issue.key} by ${payload.comment.author.displayName}`);
      // Your code: ChatOps, notifications, command parsing, etc.
      break;

    case 'comment_updated':
      console.log(`Comment updated on ${issue.key}`);
      // Your code: Audit trails, re-processing, etc.
      break;

    case 'comment_deleted':
      console.log(`Comment deleted on ${issue.key}`);
      // Your code: Audit trails, etc.
      break;

    case 'worklog_created':
      console.log(`Worklog logged on ${issue.key}`);
      // Your code: Time-tracking, billing integrations, etc.
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }

  // Return 200 to acknowledge receipt
  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: jira-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, HTTPException

load_dotenv()

app = FastAPI()

jira_secret = os.environ.get("JIRA_WEBHOOK_SECRET")


def verify_jira_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
    """Verify Jira webhook signature.

    Jira Cloud signs the raw body with HMAC-SHA256 keyed on the webhook secret
    and sends it in the X-Hub-Signature header as `sha256=<hex>` (WebSub format).
    """
    # Split the WebSub `method=signature` header (e.g. `sha256=<hex>`)
    method, _, sig = (signature_header or "").partition("=")
    if method != "sha256" or not sig:
        return False

    # Compute the expected signature over the raw body
    expected_signature = hmac.new(
        secret.encode("utf-8"),
        raw_body,
        hashlib.sha256,
    ).hexdigest()

    # Timing-safe comparison
    return hmac.compare_digest(sig, expected_signature)


@app.post("/webhooks/jira")
async def jira_webhook(request: Request):
    # Get the raw body for signature verification (do not parse before verifying)
    raw_body = await request.body()
    signature_header = request.headers.get("x-hub-signature")
    delivery_id = request.headers.get("x-atlassian-webhook-identifier")

    # Verify webhook signature before doing anything else
    if not verify_jira_webhook(raw_body, signature_header, jira_secret):
        raise HTTPException(status_code=401, detail="Invalid signature")

    # Parse the payload after verification. Jira has no event-type header —
    # the event name is in the `webhookEvent` field of the body.
    payload = json.loads(raw_body)
    event = payload.get("webhookEvent")
    issue = payload.get("issue", {})

    print(f"Received {event} event (delivery: {delivery_id})")

    # Handle the event based on its `webhookEvent` type
    if event == "jira:issue_created":
        print(f"Issue created {issue.get('key')}: {issue.get('fields', {}).get('summary')}")
        # Your code: Sync to external system, auto-assign, notify, etc.

    elif event == "jira:issue_updated":
        changelog = payload.get("changelog", {})
        print(f"Issue updated {issue.get('key')}: {changelog.get('items')}")
        # Your code: Track status changes, trigger automations, etc.

    elif event == "jira:issue_deleted":
        print(f"Issue deleted {issue.get('key')}")
        # Your code: Clean up mirrored records, etc.

    elif event == "comment_created":
        comment = payload.get("comment", {})
        author = comment.get("author", {}).get("displayName")
        print(f"Comment on {issue.get('key')} by {author}")
        # Your code: ChatOps, notifications, command parsing, etc.

    elif event == "comment_updated":
        print(f"Comment updated on {issue.get('key')}")
        # Your code: Audit trails, re-processing, etc.

    elif event == "comment_deleted":
        print(f"Comment deleted on {issue.get('key')}")
        # Your code: Audit trails, etc.

    elif event == "worklog_created":
        print(f"Worklog logged on {issue.get('key')}")
        # Your code: Time-tracking, billing integrations, etc.

    else:
        print(f"Unhandled event: {event}")

    # Return 200 to acknowledge receipt
    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)

From hookdeck/webhook-skills ↗

Or install the Jira webhooks skill:

npx skills add hookdeck/webhook-skills --skill jira-webhooks

Common failures

No secret on the webhook

Jira only sends X-Hub-Signature when the webhook has a secret. If the header is missing, set one on the webhook. A REST response shows isSigned: true when it's there.

It's an app webhook

Connect descriptor and OAuth 2.0 webhooks have a JWT in Authorization rather than X-Hub-Signature. Verify the token with your app's sharedSecret or client secret.

Body changed before verification

The HMAC covers the payload contents, so compute it over the body as you received it, not over parsed JSON. Payloads can contain Unicode, so handle them as UTF-8.

Hard-coded method

The header is method=signature, and the value starts with sha256= today. Atlassian says Jira might use another method in future, so read the method and reject one you don't support.

From Hookdeck's Jira guide

Let Event Gateway verify Jira signatures.

Event Gateway verifies the signature on each Jira delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Jira. Facts are compiled from public sources and linked inline.