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:
class Response extends Action\Action implements CsrfAwareActionInterface
public function __construct(
public function execute()
public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
public function validateForCsrf(RequestInterface $request): ?bool
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.
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.