Pergunta

Why Form Key is added in every page In Magento 2 as a hidden input type.

<input type="hidden" value="dEOXfL0kxDc8W4Yt" name="form_key">

I observed how it is generated. Is there any specific reason for adding this ?

I found the related question here but no answer.

Any help.

Foi útil?

Solução

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

This can be dangerous because someone could theoretically create their own form and post to any form handler controller action in your store. CSRF protection essentially ignores any post which fail a check on the included form_key parameter with the form post.

<?php echo $this->getBlockHtml('formkey')?>

It tells Magento to look for a layout block with the name "formkey" and output it. In Magento this is usually some file which has this in it:

<div><input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" /></div>

This instructs Magento to output and store a unique form key for a user session. All CSRF-protected Magento controller actions will verify against this before doing anything of value.

All Menu Items have an additional URL parameter named key, with a corresponding value

key/ed2ddfe814ba40acb42b6fd4e95be717d32528860c3960d5e178b50e3691e0b0/

This special code is required for all URLs, and is here to help prevent cross site script attacks. If you fail to include this key with your URL, Magento will reject the request as invalid.

This URL key is why we need to create a Menu Item in the first place — without Magento generating a URL key for us, there’s no simple safe way to access a standard admin controller.

Outras dicas

You can add formkey by this code:

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$FormKey = $objectManager->get('Magento\Framework\Data\Form\FormKey'); 
?>

<!-- Hidden form key field after <form> tag -->
<input name="form_key" type="hidden" value="<?php echo $FormKey->getFormKey();?>">
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top