I need to done an ajax request in Magento 2. But for security purpose, I need to check XSS attacks all possible case. In Magento 1 form key validation and in Magento 2 form key validation is quite different. I need to validate if the form key match or not. One thing is customer may be logged in or logged out. So I can't validate by customer session.
var formKey = jQuery("[name='form_key']").val();
jQuery.ajax({
url: "<?php echo $baseUrl.'testing/test/index';?>",
type: "POST",
data: {form_key:formKey},
success: function(response){
try {
console.log(response);
}catch(err) {}
}
});
Now from the controller, I need to validate for XSS attack.
2 Answers 2
From the client side, we can get the form key from cookie:
$.mage.cookies.get('form_key'); // jQuery.mage.cookies.get('form_key');
In your ajax controller, you use Magento\Framework\Data\Form\FormKey\Validator; for form key validation.
$this->formKeyValidator->validate($this->getRequest())
Take a look at Magento\Customer\Controller\Account\CreatePost to see more details.
-
thanks, bro it's work getting a reference from Magento\Customer\Controller\Account\CreatePost. but does this lines is Magento 2 code $.mage.cookies.get('form_key');Shuvankar Paul– Shuvankar Paul2018年11月26日 18:33:33 +00:00Commented Nov 26, 2018 at 18:33
So Final Code is
Frontend phtml Files: this will load the from key
<?php
//-- form key load
echo $this->getBlockHtml('formkey');
?>
Ajax Request
var formKey = jQuery("[name='form_key']").val();
jQuery.ajax({
url: "<?php echo $baseUrl.'testing/test/index';?>",
type: "POST",
data: {form_key:formKey},
success: function(response){
try {
console.log(response);
}catch(err) {}
}
});
Controller Code
<?php
namespace Equaltrue\Themeoption\Controller\Taxmode;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\App\ObjectManager;
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var Validator
*/
private $formKeyValidator;
/**
* @param Context $context
* @param Validator $formKeyValidator
*/
public function __construct(
Context $context,
Validator $formKeyValidator = null
)
{
$this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
parent::__construct($context);
}
public function execute()
{
if ($this->getRequest()->isPost() && $this->isAjax() && $this->formKeyValidator->validate($this->getRequest())) {
echo "this post & ajax & valid request.";
}
}
/*
* Check Request is Ajax or not
* @return boolean
* */
protected function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
}