How To Bypass CSRF Validation For Certain Requests In Magento 2
As per the Wikipedia,
Cross-site request forgery, also known as one-click attack or session riding or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts.
In simpler terms, a user is tricked into submitting a web request that they did not want to, in a CSRF attack.
Magento 2 allows the protection against CSRF attacks for security purpose. However, there are certain scenarios where one needs to bypass CSRF validation for certain requests in Magento 2.
For example, I had to implement a feature where the user is redirected to the home page after successful payment in a custom payment method. But the issue was, “Invalid Form Key” error.
This error occurs when the CSRF token has either expired, or the token was incorrectly implemented. In order to solve the “Invalid form key” error, follow the below method:
Method to bypass CSRF validation for certain requests in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php namespace Vendor\Extension\Controller\Checkout; use Magento\Framework\App\Action; use Magento\Framework\App\CsrfAwareActionInterface; use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\RequestInterface; class Response extends Action\Action implements CsrfAwareActionInterface { public function __construct( Action\Context $context, ) { parent::__construct($context); } public function execute() { } public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException { return null; } public function validateForCsrf(RequestInterface $request): ?bool { return true; } } |
Any doubts about the topic? Feel free to mention them in the Comments section below. I’d be happy to help you out asap.
Do share the solution with Magento community via social media.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hello!
I have a problem I hope you can help me with. When Magento 2 Bypass CSRF Validation code clears the customer session, checkout session. How do i keep it?
Hello anh,
It’s an issue of cookie.
Try this:
https://github.com/Veriteworks/CookieFix
Thank You