Disabling CSRF on Specific Route via Middleware

I was lately working with PayPal API on my Laravel project. In the process of coding and testing for Instant Payment Notification (IPN) part, I got an issue with csrf token. The issue was mainly with the POST request to the application via external service, so it threw TokenMismatchException via the VerifyCsrfToken middleware.

One best thing is Laravel ships with CSRF enabled by default for each HTTP request that enters the application, which is made really easy, it handles automatically.

If your application consumes third-party API service, that service may be a webhook to notify about any event and that sends HTTP request to your application. You need to be aware that Laravel filters the request that enters without csrf token, as it monitors all request entering into the application for security reason.

There is a good solution as well, and that also ships with the framework by default. See below how to disable checking csrf token for specific routes in your application, and that fixed my issue as well.

app/Http/Middleware/VerifyCsrfToken.php

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/webhook/paypal/*',
    ];

 

You could specify multiple URLs on that array if you would like to exclude other routes.

Conclusion

Thanks for reading this post up to the end, if you think this post is worth reading, feel free to share with others, also if you have feedback please post in the comment section below.

Happy Coding!