TokenMismatchException when Mailgun webhooks hit Laravel endpoint

I’m having trouble with my Laravel 4.1 app receiving webhook notifications from Mailgun. Every time Mailgun tries to send a POST request to my application endpoint, Laravel blocks it and throws this error:

throw new Illuminate\Session\TokenMismatchException;

This happens because Mailgun’s webhook requests don’t include the CSRF token that Laravel expects for POST requests. I’ve been trying different approaches but can’t seem to find the right way to handle this. The webhook needs to work automatically without any user interaction, so I can’t just add a token to the form. Has anyone dealt with this before? What’s the proper way to allow Mailgun webhooks while keeping CSRF protection active for the rest of the application?

for sure! just update the $except array in app/Http/Middleware/VerifyCsrfToken.php to include your webhook route. this way, it won’t check for CSRF tokens and the webhooks will go through just fine!

To resolve the issue, you can create a custom route group that excludes CSRF middleware specifically for your Mailgun webhook. Since you’re on Laravel 4.1, ensure that your webhook route is defined before the Route::filter call in routes.php. This way, your CSRF setup remains intact for all other routes. Additionally, you should implement Mailgun’s signature verification by hashing the timestamp and token parameters they send with your API key to ensure the request is legitimate. This approach is more reliable than trying to adapt external services to work with Laravel’s CSRF tokens.

Laravel 4.1 handles this differently than newer versions. You’ll need to modify the CSRF filter in your filters.php file directly. Just add a condition that skips CSRF verification for your webhook route by checking the request path first.

Try this in your Route::filter:

Route::filter('csrf', function()
{
    if (Request::path() !== 'your-mailgun-webhook-path') {
        if (Session::token() !== Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }
    }
});

This keeps CSRF protection everywhere else but lets Mailgun hit your webhook without problems. Don’t forget to swap ‘your-mailgun-webhook-path’ with your actual route.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.