Custom forms in the shop stopped working after a Magento update. “Invalid Form Key” error in logs. Custom AJAX endpoints threw CSRF exceptions on every request. Fix time: 2 hours.
Symptoms
- Forms return “Invalid Form Key. Please refresh the page.”
- AJAX POST to custom controllers ends in redirect or 403
- Problem appeared after updating Magento to 2.4.x
Solution
<?php
// Option A: Implement CsrfAwareActionInterface
class MyController extends \Magento\Framework\App\Action\Action
implements \Magento\Framework\App\CsrfAwareActionInterface
{
public function createCsrfValidationException(
\Magento\Framework\App\RequestInterface $request
): ?\Magento\Framework\App\Request\InvalidRequestException {
return null;
}
public function validateForCsrf(
\Magento\Framework\App\RequestInterface $request
): ?bool {
$apiKey = $request->getHeader('X-Api-Key');
return $apiKey === $this->config->getApiKey();
}
}
// JavaScript - add form_key to every AJAX POST
require(['jquery', 'mage/cookies'], function($) {
$(document).ajaxSend(function(event, xhr, settings) {
if (settings.type === 'POST') {
var formKey = $.mage.cookies.get('form_key');
if (formKey && settings.data) {
settings.data += '&form_key=' + formKey;
}
}
});
});
Takeaways
CSRF protection in Magento 2.4+ is enabled by default for all controllers. Custom endpoints require either including form_key in the request or implementing CsrfAwareActionInterface with custom validation logic (e.g. API key, JWT token).
