Site icon MageComp Blog

How to Bypass CSRF Validation in Magento 2?

How to Bypass CSRF Validation in Magento 2

Bypassing CSRF (Cross-Site Request Forgery) validation in Magento 2 is generally not recommended, as it can expose your store to significant security risks. CSRF protection is implemented to prevent unauthorized actions on behalf of authenticated users. However, there may be specific scenarios where you need to bypass CSRF validation, such as when integrating third-party services or handling custom API requests. This blog will guide you through the steps to bypass CSRF validation in Magento 2, but be cautious and understand the security implications.

Understanding CSRF in Magento 2

CSRF is a security mechanism that ensures requests made to your Magento 2 store are legitimate and originate from the authenticated user. Magento 2 uses a CSRF token to validate POST, PUT, and DELETE requests to prevent malicious attacks.

When to Bypass CSRF Validation?

Bypassing CSRF validation should only be considered when:

Steps to Bypass CSRF Validation in Magento 2:

Step 1: Create a di.xml file in the below-given path

app\code\Vendor\Extension\etc\di.xml

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\Request\CsrfValidator">
        <plugin name="csrf_validator_skip" type="Vendor\Extension\Plugin\Csrfvalidatorskip" />
    </type>
</config>

Step 2: Create a Csrfvalidatorskip.php file in the below path.

app\code\Vendor\Extension\Plugin\Csrfvalidatorskip.php

Now add the following code

<?php
namespace Vendor\Extension\Plugin;

class Csrfvalidatorskip
{
    /**
     * @param \Magento\Framework\App\Request\CsrfValidator $subject
     * @param \Closure $proceed
     * @param \Magento\Framework\App\RequestInterface $request
     * @param \Magento\Framework\App\ActionInterface $action
     */
    public function aroundValidate(
        $subject,
        \Closure $proceed,
        $request,
        $action
    ) {
        // replace your route name with yourroutename
        if ($request->getModuleName() == 'yourroutename') {  
            return; // Skip CSRF check
        }
        $proceed($request, $action); // Proceed Magento 2 core functionalities
    }
}

Conclusion:

Bypassing CSRF validation in Magento 2 can be necessary in specific cases, but it comes with significant security risks. Always weigh the need to bypass against the potential vulnerabilities it may introduce. Implement the bypass in a controlled manner, and take additional security measures to protect your Magento 2 store. If possible, seek alternative solutions that do not require bypassing CSRF validation.

By following this guide, you can safely bypass CSRF validation when necessary, ensuring that your Magento 2 store remains secure and functional.

Happy Coding!

Exit mobile version