Mohamed Abbas | Architect Magento | Tech Blogger | Magento Trainer

Mohamed Abbas
Mohamed Abbas
Architect Magento | Tech Blogger | Magento Trainer

CSRF and X-Requested-With Skip Code in Magento

Magento, a robust e-commerce platform, ensures security by implementing several validation mechanisms. Among these is Cross-Site Request Forgery (CSRF) protection, which prevents unauthorized actions performed on behalf of an authenticated user. Additionally, Magento often relies on the X-Requested-With header to validate AJAX requests.

However, during custom module development or integrations with third-party services, there might be a need to bypass these validations under controlled scenarios. This article explains how to safely skip CSRF validation and handle the X-Requested-With header in Magento without compromising security.

What is CSRF and X-Requested-With?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a browser into performing actions on a trusted site where the user is logged in. Magento’s CSRF protection validates incoming requests using tokens to prevent such exploits.

X-Requested-With is an HTTP header commonly used to identify AJAX requests. Magento uses this header to distinguish server-originated requests from direct access attempts.

Why Skip CSRF and X-Requested-With Validation?

There are specific scenarios where skipping these validations is necessary:

  • Integrating with third-party APIs or services that don’t send CSRF tokens.
  • Allowing public or non-AJAX access to specific controllers for external operations.
  • Custom module development where certain endpoints don’t require strict validation (e.g., webhook callbacks).

Skipping CSRF Validation

To disable CSRF validation for a specific controller action in Magento 2, you need to create a custom webapi_rest or webapi_soap configuration. However, for custom modules using regular controllers, you can extend Magento’s CsrfAwareActionInterface.

Here’s how:

  1. Update Your Controller File
    Add the CsrfAwareActionInterface to your custom controller and implement its methods:
				
					<?php

namespace Abbasm\Csrf\Controller\Custom;

use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;

class Example extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface
{
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null; // Skip CSRF validation
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true; // Bypass CSRF
    }

    public function execute()
    {
        // Your controller logic here
    }
}

				
			

Skipping X-Requested-With Header Validation

The X-Requested-With header is often validated for AJAX-specific requests. To skip this validation, you can override the validateRequest method in your custom controller.
Here’s how:

				
					<?php

namespace Abbasm\Csrf\Controller\Custom;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Action\Action;

class Example extends Action
{
    public function execute()
    {
        // Disable X-Requested-With validation logic
        $request = $this->getRequest();

        if (!$request->isAjax()) {
            // Your custom logic for non-AJAX requests
        }

        // Continue with controller logic
    }
}

				
			

This ensures that your endpoint works seamlessly even without the X-Requested-With header.

Security Implications

While skipping these validations may be required in some scenarios, it’s essential to follow security best practices:

  1. Restrict Access
    • Limit skipped validations to specific endpoints.
    • Use IP whitelisting or authentication tokens.
  2. Sanitize Input
    • Validate all incoming data rigorously to avoid injection attacks.
  3. Log Requests
    • Track requests to endpoints with skipped validations to monitor potential misuse.

Conclusion

Magento’s CSRF and X-Requested-With header validations are vital for securing e-commerce operations. However, certain customizations require bypassing these validations carefully and thoughtfully. By understanding the implications and following best practices, you can ensure a smooth integration while maintaining the platform’s security standards.
Happy coding! 😊