Magento CSRF protection

2019-03-20 10:24发布

问题:

I am looking at custom forms in Magento. I saw these tutorials

http://fastdivision.com/2012/03/29/diy-magento-create-ajax-login-registration-forms-for-your-magento-theme/

http://inchoo.net/ecommerce/magento/magento-email/magento-custom-email-contact-form-with-notification-system/

I did not see any mention of CSRF prevention, like checking a client token with one stored in a user session. I also looked in the Magento Contact Us form, and saw this but I do not think it relates to CSRF:

<input type="text" name="hideit" id="hideit" value="" style="display:none !important;">

Does Magento have any default code for preventing CSRF? Does the $this->getRequest()->getParams() method of Mage_Core_Controller_Front_Action do anything automatically to prevent CSRF that I may be missing?

回答1:

It's on the end programmer user to use their own CSFR/nonce protection scheme, unless they're creating a page/form in the backend admin console. The Magento admin console application has this protection for all its pages/urls by default.

Check out _validateSecretKey in app/code/core/Mage/Adminhtml/Controller/Action.php and the getSecretKey method in app/code/core/Mage/Adminhtml/Model/Url.php. This could easily be extended to your own forms on the frontend.



回答2:

There's actually a frontend CSRF token validation method in Magento you can use to add a unique session-based form key to your custom form and validate it in the controller's action.

To send a CSRF form key with the request when submitting a form insert the <?php echo $this->getBlockHtml('formkey') ?> code into the form's body.

This will generate an input like this: <input type="hidden" value="unique16codehere" name="form_key">. To validate the key use the _validateFormKey() method in the respective controller's action.