# Securing the Endpoint (/docs/webhooks/getting-started/securing-the-endpoint)

Check the spoke-signature header, a hex HMAC-SHA256 of the request body, to confirm a webhook came from Spoke.

Spoke provides a way for you to be sure that the message you are receiving
originated from us and not from some third party.

> **Warning**
>
> Verify the signature on every request before you act on it. Your endpoint is
> public, so anyone who knows the URL can send it a request that looks like an
> order event.

## The 'spoke-signature' header

Spoke includes, on every request, a header called `spoke-signature`. Use it to
check that the message your webhook is handling comes from Spoke and not from a
third party.

The header holds the hex-encoded
[HMAC](https://en.wikipedia.org/wiki/HMAC)-SHA256 of the raw request body, using
your webhook secret as the key. Use the secret as text; do not hex-decode it.
Spoke computes the HMAC over the exact bytes it sends.

## Obtaining your webhook secret

Spoke uses a webhook secret to sign all the requests sent to your endpoint. This
secret consists of 32 characters. For example:
`7fd4eb15359c04280311116c6c597041`

To obtain your webhook secret:

1. Open **Settings > Integrations** in Connect, find the **Webhooks** section,
   and select **Reveal** under **Secret key**:

   ![Reveal Secret](/img/settings/reveal_secret.png)

1. Then select **Copy** and store the secret where your endpoint can read it:

   ![Copy Secret](/img/settings/copy_secret.png)

> **Warning**
>
> You should **never** share this secret or commit it to source control. Anyone
> who has it can forge requests to your endpoint.
>
> If you think your secret has been compromised, select **Generate new key**, copy
> the new key, then select **Save** and confirm with **Save new key**. Spoke signs
> every request it sends after the change with the new secret, including retries
> of earlier events, so update your endpoint at the same time.

## Securing your endpoint with the 'spoke-signature' header

To secure your endpoint, recalculate the signature from the raw body with your
secret and check that it matches the one you received:

1. Read the raw body as a string, before any JSON parsing.
1. Compute the HMAC-SHA256 of that string with your secret, as lowercase hex.
1. Compare it to the `spoke-signature` header with a constant-time comparison.
1. Reject the request when they differ. Parse the JSON only after they match.

Parsing the JSON and serializing it again can change whitespace or key order,
which changes the signature. Always use the body as received.

### Example

With the secret `7fd4eb15359c04280311116c6c597041` and this body:

```text title="Request body"
{"type":"order.out_for_delivery","version":"v1","created":1779004800000,"data":{"id":"orders/W3kJpzQm9q4LV2BdH7sNuT"}}
```

the header is:

```text title="Request header"
spoke-signature: a3cf1eea3ac26ee90c8386979506619faee77f2b6e36d81d6698adcd7df3a488
```

Use this pair to check your implementation. Real bodies are larger because
`data` is a full [Order](/docs/models/order).

### Reference implementations

We present here some reference implementations:

```javascript tab="Node"
// Using express

const express = require('express')
const crypto = require('crypto')

const app = express()

// The signing secret from Settings > Integrations in Connect
const secret = process.env.SPOKE_WEBHOOK_SECRET

// Keep the body as a string, so the signature is computed on the raw bytes
app.post(
  '/spoke-webhook',
  express.text({ type: '*/*' }),
  (request, response) => {
    const receivedSignature = request.get('spoke-signature')

    if (!receivedSignature) {
      return response.status(400).send({ message: 'Message invalid' })
    }

    const expectedSignature = crypto
      .createHmac('sha256', secret)
      .update(request.body)
      .digest('hex')

    if (
      expectedSignature.length !== receivedSignature.length ||
      !crypto.timingSafeEqual(
        Buffer.from(expectedSignature),
        Buffer.from(receivedSignature),
      )
    ) {
      return response.status(400).send({ message: 'Message invalid' })
    }

    const event = JSON.parse(request.body)

    // Process the event here

    return response.sendStatus(200)
  },
)
```

```python tab="Python"
# Using FastAPI

import hashlib
import hmac
import json
import os

from typing import Optional

from fastapi import FastAPI, Header, HTTPException, Request, Response

app = FastAPI()

# The signing secret from Settings > Integrations in Connect
secret = os.environ["SPOKE_WEBHOOK_SECRET"].encode()

@app.post("/spoke-webhook")
async def receive_webhook(
    request: Request, spoke_signature: Optional[str] = Header(None)
):
    if not spoke_signature:
        raise HTTPException(status_code=400, detail="Message invalid")

    raw_body = await request.body()
    expected_signature = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(
        expected_signature.encode(), spoke_signature.encode()
    ):
        raise HTTPException(status_code=400, detail="Message invalid")

    event = json.loads(raw_body)

    # Process the event here

    return Response(status_code=200)
```