> For the complete documentation index, see [llms.txt](https://docs.formsort.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.formsort.com/integrations/getting-data-out/signed-requests.md). Agents can also search and read this documentation through its [MCP server](https://docs.formsort.com/~gitbook/mcp).

# Signed requests

Sign events and webhooks

### Signing requests <a href="#signing-requests" id="signing-requests"></a>

Both webhooks and events can be signed for extra security.

#### Signing webhooks

For webhooks if you'd like the requests to be signed to ensure that they are authentic requests from formsort, you can enable the `sign` security. Read more about creating a webhook [here](https://docs.formsort.com/integrations/integration-reference/webhooks.md).

You can also rotate your webhook signing key from **Security** → **Signing Keys**. To avoid interruptions, Formsort allows existing published forms to continue using their previous signing key until they're republished. See [Rotating webhook signing keys](#rotating-webhook-signing-keys) for instructions.

#### Signing events

All events for `variant_revision_published` are signed by default. The signature for verfication  can be found on the "Events" page.

&#x20;

<figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2F3cuApA7NFR6WLQlIOdtK%2FScreen%20Shot%202022-11-03%20at%2010.25.38.png?alt=media&amp;token=a10422b6-85c5-4f04-9054-e1a22cd5a713" alt=""><figcaption><p>Click "Show signing key"</p></figcaption></figure>

**The signing key is generated by Formsort and is different between Events and Webhooks.**

### Rotating webhook signing keys

You can rotate your webhook signing key in Formsort Studio to replace an existing key with a new one. Rotating your key periodically is a good security practice, and Formsort allows you to make this transition without interrupting webhook deliveries.

To rotate a signing key, you'll need the **Owner, Admin, or Engineer** role in your Formsort workspace.

Before getting started, make sure you have a copy of your current signing key. Once you rotate the key, **only the new key will be visible in Studio**. You'll need both keys during the transition to ensure your webhook endpoint continues accepting requests.

{% hint style="info" %}
Rotating your webhook signing key only affects **answer webhooks**. The signing key used for [event notifications](https://docs.formsort.com/event-subscriptions.md) is managed separately and will not change.
{% endhint %}

#### Step 1: Rotate your signing key

1. In Formsort Studio, navigate to **Security → Signing Keys**.
2. Find the **Webhook answers integration signing key** row.
3. Click the **⋮** menu and select **Rotate key**.
4. Click **OK** to confirm.

Once rotated, the new signing key will be available on the Security page.

**Your existing published forms will continue using the previous signing key** until you republish them. This gives you time to update your webhook endpoint before switching over.

<div align="left"><figure><img src="https://1036686854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJPnL__mOdr_mLZ8nwf%2Fuploads%2FaAb7b7JRv8RIwtbugbs8%2Fimage.png?alt=media&amp;token=66e2a502-ecc3-4afe-b9ec-2df72fefa913" alt="" width="563"><figcaption></figcaption></figure></div>

#### Step 2: Update your webhook endpoint

Copy the new signing key from Studio and update your webhook receiver to accept signatures generated using either the previous key or the new key.

During this transition, your endpoint should consider a webhook valid if its signature matches **either signing key**. You can continue using your existing signature verification method, checking the incoming signature against each key.

To test your updated endpoint:

1. Open a form's webhook settings in Studio.
2. Click **Send test** to send a test webhook.
3. Confirm that your endpoint successfully receives and validates the request.

Test webhooks are signed using the **new signing key immediately after rotation**, even before you've republished your forms.

#### Step 3: Republish your forms

Once your endpoint is ready to accept both signing keys, republish each form that sends signed webhooks.

Republishing updates the signing key used for new responders, so their webhooks will now be signed using the new key.

If you also want responders who have already started a form to use the new signing key, enable [**Supercede past revisions of variant**](https://docs.formsort.com/core-concepts/versioning-in-formsort-deploying.md#superseding-past-revisions-of-a-variant) when republishing.

Without this option, existing responders will continue using the previous signing key until they finish their original form revision.

#### Step 4: Continue accepting the previous key

We recommend keeping both signing keys configured on your webhook endpoint for a short period after republishing.

You may still receive webhooks signed using the previous key, including requests from:

* Responders who started a form before it was republished.
* Previously abandoned form sessions that are resumed.
* Retries of webhook deliveries originally signed with the previous key.

{% hint style="info" %}
If possible, consider logging which signing key successfully validates each incoming request. This can help you determine whether older webhook deliveries are still reaching your endpoint.
{% endhint %}

#### Step 5: Remove the previous key

Once you've confirmed that incoming webhooks are no longer being signed with the previous key, you can remove it from your webhook endpoint's verification configuration.

Your endpoint should now verify incoming webhooks using only the new signing key.

### How to verify a signature

To generate the signature for verification, use the original HTTP request body (aka JSON payload) and:

1. Hash the request body with SH256, encrypting it with signing key.
   1. You can obtain the key in the Integrations tab when this option is enabled.
2. Base64 encode the result in a URL-safe-way, using `-` and `_` instead of the `+` and `/` characters. This is necessary as Formsort sends the signature in an HTTP header.
3. Remove the trailing `=` signs. Those are often generated by the hashing libraries as padding.

Sample implementations of the signature code follow, however these examples demonstrate signature verification using a single signing key. They do not include the additional verification logic needed during key rotation.

To avoid interrupting webhook deliveries when rotating your signing key, configure your webhook endpoint to temporarily accept signatures generated using **either the previous or new signing key**.

{% tabs %}
{% tab title="Python" %}

```python

import base64
import hashlib
import hmac


def as_bytes(v):
    return v.encode("utf8")


def hmac_sign(signing_key, original_request_body):  # unmodified, a jsonified string
    key = as_bytes(signing_key)
    message = as_bytes(original_request_body)
    return (
        # Note:
        # 1. for url safety, use - and _ characters instead of + and / respectively
        # 2. remove the padding = signs at the end of the signature
        base64.urlsafe_b64encode(
            hmac.new(key, message, hashlib.sha256).digest())
            .rstrip(b"=")
            .decode("utf8")
    )

```

{% endtab %}

{% tab title="Javascript (Express)" %}
To verify a signature in Javascript, the original request buffer can be verified with the signing key like follows:

```javascript
import crypto from 'crypto';

const hmacSign = (signingKey, originalRequestBuffer) => {
    const key = Buffer.from(signingKey, 'utf8');
    return (
        crypto
            .createHmac('sha256', key)
            .update(originalRequestBuffer)
            .digest('base64')
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '')
    );
}
```

\
If you are using `express` as your webserver, and have enabled JSON body parsing with `express.json()` be careful that you are signing the original body buffer and not the parsed JSON. Signing a stringified `req.body` is not reliable due to differences in whitespace between implementations and settings.

The simplest way to do this is to ensure that routes for receiving Formsort webhooks do not apply the JSON middleware.

Using the `hmacSign` function above, assuming a `SIGNING_KEY` environment variable, the following will sign requests from Formsort:

```javascript
import crypto from 'crypto';
import express from 'express';
import bodyParser from 'body-parser';
const PORT = 8080;

const app = express();

app.use((req, res, next) => {
  if (req.header('x-formsort-secure') === 'sign') {
    // Signed formsort requests require verification of the raw body content
    bodyParser.raw({ type: 'application/json' })(req, res, next);
  } else {
    express.json()(req, res, next);
  }
});

const hmacSign = (signingKey, originalRequestBuffer) => {
    const key = Buffer.from(signingKey, 'utf8');
    return (
        crypto
            .createHmac('sha256', key)
            .update(originalRequestBuffer)
            .digest('base64')
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '')
    );
}

app.post('/formsort-webhook', (req, res) => {
  const signature = hmacSign(process.env.SIGNING_KEY, req.body);
  if (signature !== req.header('x-formsort-signature')) {
    return res.status(401).json({ message: 'Formsort signature mismatch' });
  }

  const answers = JSON.parse(req.body);
  return res.json({
    message: 'Well now, it looks like you are all good.',
    answers,
  });
});

app.listen(PORT, () => {
  console.log(`listening on port ${PORT}`);
});
```

{% endtab %}
{% endtabs %}

When signing is enabled, Formsort will send the following additional HTTP headers on webhook requests﻿If signature is enabled, then `X-Formsort-Secure` will have the value of `"sign"` and `X-Formsort-Signature` will have the signature itself.

| Header                 | Value      |
| ---------------------- | ---------- |
| `X-Formsort-Secure`    | sign       |
| `X-Formsort-Signature` | {the hash} |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.formsort.com/integrations/getting-data-out/signed-requests.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
