Retrieving the Form Key from Magento 2.0 for Custom Login Pages
As a developer new to Magento, you’re facing a common challenge when trying to create a custom login page outside of the platform: obtaining the form_key value required for secure form submissions. In this post, we’ll explore two approaches to achieve thisâone using JavaScript and another with PHPâand provide best practices for a robust solution.
Understanding the Form Key in Magento
The form_key is a crucial security measure introduced in Magento 2.0 to prevent Cross-Site Request Forgery (CSRF) attacks by ensuring that form submissions originate from valid pages within your store. It’s generated as a random string and tied to each user session.
Retrieving the Form Key with JavaScript
Current Approach: XHR to Fetch the Entire Page
Your initial solution uses an XMLHTTPRequest to fetch the entire Magento homepage, parse its DOM, and extract the form_key value. While this approach works in a local development environment, it raises several concerns:
- Performance Issues: Loading the entire page for a single form key is inefficient.
- Security Risks: Exposing your store’s content to external scripts.
- Maintenance Challenges: Changes in Magento’s layout might break your script.
Improved JavaScript Solution: Direct API Endpoint
Instead of fetching an entire page, create a dedicated API endpoint within Magento that returns the current form_key value as JSON:
- Create a new controller under
app/code/Vendor/Module/Controller/Local/Formkey.php.
namespace Vendor\Module\Controller\Local;
use Magento\Framework\App\Action;
use Magento\Framework\App\ResponseInterface;
class FormKey extends Action
{
public function execute(): ResponseInterface
{
$formKey = $this->_request->getSession()->getFormKey();
return $this->jsonResponse(['form_key' => $formKey]);
}
}
- Add the following route in
app/code/Vendor/Module/etc/frontend/routes.xml:
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App etc/routes.xsd">
<route id="vendor_formkey_index_index">
<frontName>vendor</frontName>
<action>\Vendor\Module\Controller\Local\FormKey::execute</action>
</route>
</routes>
- Fetch the
form_keyin your JavaScript:
fetch('https://your-magento-site.com/vendor/formkey/index')
.then(response => response.json())
.then(data => {
const formKey = data.form_key;
console.log(formKey);
// Pass the form key to your custom login page
});
Benefits of this Approach
- Direct and efficient API access.
- Minimal performance impact compared to fetching an entire page.
- Improved security by limiting exposed data.
- Easier maintenance and scalability.
Retrieving the Form Key with PHP: A Note on Security
While you mentioned being open to creating a PHP file within Magento to generate the form_key, it’s crucial to stress that this approach introduces significant security risks. Generating sensitive data like form keys in an accessible external PHP file is a serious vulnerability, as it exposes your Magento install to potential attackers.
Conclusion: Choosing the Right Approach for Your Needs
For most use cases, especially in production environments, I strongly recommend implementing the JavaScript solution using a dedicated API endpoint within Magento. This approach offers the best balance between security, performance, and maintainability.
However, if you’re working on a local development environment or need to access form keys programmatically from PHP scripts within your project, consider the following:
- Implement the API-based JavaScript solution for your custom login page.
- For internal PHP use-cases only (never expose this in production), create a controller similar to the one described above and access it securely through Magento’s built-in routing system.
Remember that form keys are sensitive data designed to protect your store from malicious attacks, so always prioritize security when handling them in your custom integrations.