magento 2-“ CSRF验证程序”呈现形成窗体密钥的不同验证程序密钥

时间:2018-08-14 07:33:03

标签: php magento2

我的表单的Csrf无法验证,并且始终返回null。

if($this->formKeyValidator->validate($this->getRequest())){
   //do something 
} 

我调查了一下,发现我的自定义表单的Csrf密钥返回的值不同于验证器密钥产生的值:

\magento\framework\Data\Form\FormKey\Validator::validate

这就是我所做的:

阻止:

namespace Test\Aup\Block\Registration;
class AccountDetails extends Template
{
    protected $formKey;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context, 
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\Form\FormKey $formKey,
        $data = []
    ) {
        $this->formKey   = $formKey;
        $this->_registry = $registry;

        parent::__construct($context, $data);
    }
    public function getFormKey()
    {
      return $this->formKey->getFormKey();
    } 
}

查看:

Test\Aup\view\frontend\templates\registration\accountdetails.phtml

 <form autocomplete="off" method="post" autocomplete="off" action="/Test/Aup/"  class="container">
     <input type="hidden" name="form_key" value="<?php echo $block->getFormKey() ?>" />

<div class="bottom-action">
    <span class="button right">
        <input  type="submit" name="submitregister" value="Continue" class="button continue"></input>
     </span>
</div>

  </form> 

控制器:

 namespace Test\Aup\Controller\Registration;
 Class Index extends \Magento\Framework\App\Action\Action

{
    protected $formKey;
    protected $formKeyValidator;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
        \Magento\Framework\Data\Form\FormKey $formKey    
    )
    {
        $this->formKeyValidator  = $formKeyValidator;
        $this->formKey           =  $formKey;
        $this->_pageFactory      = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
          echo "formKey produced from the validator: \Magento\Framework\Data\Form\FormKey\Validator";
          var_dump($this->formKey->getFormKey());

        $formKeyForValidation = $this->getRequest()->getPostValue('form_key');

        echo "post returned form Key";
        var_dump($formKeyValidator);die();

        $validFormKey = $this->formKeyValidator->validate($this->getRequest()); die();
    }
}

两个值产生完全不同的数字。因此,该测试失败了:

$this->formKeyValidator->validate($this->getRequest()))

我的Magento已安装在wampp上。

0 个答案:

没有答案