Magento 2 Form key
-
11-10-2020 - |
Question
if (!$this->_validateFormKey()) { // do something }
Any Magento 1 equivalent in Mangento 2 for _validateFormKey
function.
And Can anyone explain how and where Magento checks formkey
, when any form is submitted.
Basically I am not able to validate the formkey
in controller, My form is submitted even if change the formkey
value from inspect element.
Solution
Try following way:
protected $formKeyValidator;
public function __construct (
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
) {
$this->formKeyValidator = $formKeyValidator;
}
And then
if (!$this->formKeyValidator->validate($this->getRequest())) {
// invalid request
}
OTHER TIPS
There is also in Magento 2 a form key validator
Magento\Framework\Data\Form\FormKey\Validator
Have a look on the customer loginPost controller to see an example of its use
vendor/magento/module-customer/Controller/Account/LoginPost.php
Add formkey inside the form like below and follow the above steps for validating in controller.
<?= $block->getBlockHtml('formkey') ?>
Some previous answer is correct but I am elaborate it.
namespace Equaltrue\Themeoption\Controller\Taxmode;
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var Validator
*/
protected $formKeyValidator;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param Validator $formKeyValidator
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
)
{
$this->formKeyValidator = $formKeyValidator;
parent::__construct($context);
}
public function execute()
{
if ($this->formKeyValidator->validate($this->getRequest())) {
// form key is validate
}
}
}
Now you may face a problem if you use localhost in user like URL: http://localhost/magento2/
The Form Key from website & Magento will not match. You can check it from following Magento core file.
vendor/magento/framework/Data/Form/FormKey/Validator.php
Now you have to change localhost to 127.0.0.1 or your IP.