How to bypass CSRF validation for certain requests like payment gateway webhook?
You can add a formKey
to your request.
Magento checks in the validateRequest
function at Magento\Framework\App\Request\CsrfValidator
if the request is intance of CsrfAwareActionInterface
, not a post request, ajax or has a valide formKey
:
private function validateRequest(
HttpRequest $request,
ActionInterface $action
): bool {
$valid = null;
if ($action instanceof CsrfAwareActionInterface) {
$valid = $action->validateForCsrf($request);
}
if ($valid === null) {
$valid = !$request->isPost()
|| $request->isAjax()
|| $this->formKeyValidator->validate($request);
}
return $valid;
}
You can inject Magento\Framework\Data\Form\FormKey
and add to your request, something like this:
$requestUrl .= '?form_key=' . $this->formKey->getFormKey();