How to Add Form Key in Magento 2

How to Add Form Key in Magento 2

Adding form key in Phtml in Magento 2 is a way of preventing the cross-site request forgery.

As per Wikipedia, the cross-site request forgery means,

“An innocent end-user is tricked by an attacker into submitting a web request that they did not intend. This may cause actions to be performed on the website that can include inadvertent client or server data leakage, change of session state, or manipulation of an end user’s account. ”

When you add form key in Magento 2, you keep your site safe from spammers trying to post to your forms from other sites as if you!

If the site is vulnerable to XSRF attack, a spammer can create his/her own form and post to any form handler controller action in the Magento 2 store. The below solution enables a check on the included form_key parameter with the form post and ignores any post which fails this verification.

Implementing the below solution will tell Magento to check for a layout block with the name “formkey”, output and store that unique key for a user session.

Method to add form key in Magento 2:

  1. Create CMS Page : custom_form
  2. Create block File : BlockName.php
  3. Create customForm.phtml

    Custom Form key example:

    Note: You can also add form key using Object manager, however is not recommended

  4. Create customForm.phtml

    Custom Form key example

    That’s it.

    Any doubts on the topic can be mentioned in the Comments section below. I’d be happy to help.

    Please share the solution with Magento community via social media.

    Thank you.

Get E-commers Updates in Your Inbox

Thank you for subscribing.

Something went wrong.

5
(based on 9 Reviews)

He is been with Meetanshi for more than two years now as a Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.

Leave a reply:

Your email address will not be published.