1

The form key block is added to the content container of each page in Magento 2 by the Magento_Theme default.xml.

What is the purpose of adding this to every page in the middle of content?

https://github.com/magento/magento2/blob/2.0/app/code/Magento/Theme/view/frontend/layout/default.xml

1

Form key in Magento are a means of preventing against Cross Site Request Forgery, in short, it's to keep us safe from people trying to post to our forms (like add to cart) from other sites.

Since Magento is already adding a form key for every page, what we all need to do is, validate this form key while submitting any data from that particular page.

For an example, Wishlist module is validating this form key when we add wishlist item to the cart.

<?php
namespace Magento\Wishlist\Controller\Index;

use Magento\Framework\App\Action;
use Magento\Catalog\Model\Product\Exception as ProductException;
use Magento\Framework\Controller\ResultFactory;

class Cart extends \Magento\Wishlist\Controller\AbstractIndex
{
    ...

    /**
     * @var \Magento\Framework\Data\Form\FormKey\Validator
     */
    protected $formKeyValidator;

    ...
    public function __construct(
        ...
        \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
    ) {
        ...
        $this->formKeyValidator = $formKeyValidator;
        ...
    }

    ...
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setPath('*/*/');
        }

        ...
    }
}

Similarly, we could use this \Magento\Framework\Data\Form\FormKey\Validator class to validate our forms against CSRF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.