Search code examples
webhooksmailgun

Mailgun Webhook Access


We're currently implementing Mailgun's webhook to convert an email reply to a reply in a comment thread in our application. We set up a route to match the recipient and set the action to store(notify="https://example.com/example-endpoint"). Mailgun POSTs data to the given endpoint where we then process the message and add it to the application comment thread.

My question is this:

How do I lock down the endpoint so that Mailgun is the only entity that can post here? Is there a list of IPs that I can whitelist? Is there a special key that they send that I can validate against the private API key?


Solution

  • I found my own answer in the documentation. I should have read the documentation more closely.

    The "Securing Webhooks" section under https://documentation.mailgun.com/user_manual.html#webhooks says:

    To ensure the authenticity of event requests, Mailgun signs them and posts the signature along with other webhook parameters.

    I had to compare the signature value in the payload to a SHA256 HMAC hash of timestamp and token using the api key as the HMAC key.

    For example:

    $_POST['signature'] === hash_hmac('sha256', $_POST['timestamp'] . $_POST['token'], 'example-api-key);