How To Secure Magento 2 API
Magento 2 exposes powerful APIs that can be used to integrate with ERPs, CRMs, mobile apps, and third-party services. Because these APIs can access sensitive data such as customer information, orders, and payment-related details, securing them is critical. In this article, we’ll explore the three API authentication methods offered by Magento 2 and look at practical code examples to help you implement them securely.
Magento 2 API Authentication Methods
Magento 2 provides three main authentication mechanisms for its REST APIs:
- Token-based authentication
- OAuth-based authentication
- Session-based authentication
Each method is suited to different use cases. The following sections explain how they work and show example requests and code snippets you can use in your Magento 2 projects.
1. Token-Based Authentication
What Is Token-Based Authentication?
Token-based authentication issues an encrypted token after a user successfully logs in. The client then sends this token with each API request instead of sending username and password every time.
High-level flow:
- Request: User sends credentials to the Magento API.
- Verification: Magento validates the credentials.
- Token Issue: Magento returns a signed access token.
- Storage: Client stores the token (typically in local storage or memory).
- Expiration: Token remains valid until it is revoked, expired, or the user logs out.
Magento 2 Token Endpoints
- Customer Token:
/V1/integration/customer/token - Admin Token:
/V1/integration/admin/token
cURL: Get Customer Token
curl -X POST "https://your-domain.com/rest/V1/integration/customer/token" \
-H "Content-Type: application/json" \
-d '{
"username": "customer@example.com",
"password": "CustomerPassword123"
}'
Response (example):
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."
cURL: Get Admin Token
curl -X POST "https://your-domain.com/rest/V1/integration/admin/token" \
-H "Content-Type: application/json" \
-d '{
"username": "admin_user",
"password": "AdminPassword123"
}'
Use the Token to Call a Protected Endpoint
After receiving the token, pass it as a Bearer token in the Authorization header when
accessing other REST resources.
curl -X GET "https://your-domain.com/rest/V1/customers/me" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi..."
PHP: Generate Tokens Programmatically in Magento 2
You can generate customer and admin tokens in your custom module using Magento service interfaces.
<?php
namespace Vendor\Module\Model;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Integration\Api\AdminTokenServiceInterface;
class TokenGenerator
{
protected $customerTokenService;
protected $adminTokenService;
public function __construct(
CustomerTokenServiceInterface $customerTokenService,
AdminTokenServiceInterface $adminTokenService
) {
$this->customerTokenService = $customerTokenService;
$this->adminTokenService = $adminTokenService;
}
/**
* Generate token for a customer.
*/
public function getCustomerToken(string $username, string $password): string
{
return $this->customerTokenService->createCustomerAccessToken(
$username,
$password
);
}
/**
* Generate token for an admin user.
*/
public function getAdminToken(string $username, string $password): string
{
return $this->adminTokenService->createAdminAccessToken(
$username,
$password
);
}
}
Security tips for token-based authentication:
- Always use HTTPS, never expose tokens over HTTP.
- Store tokens securely on the client side.
- Rotate tokens regularly and revoke when users are disabled.
- Limit token scope with appropriate ACL and role configuration.
2. OAuth-Based Authentication
What Is OAuth-Based Authentication?
OAuth 1.0a allows third-party applications (integrations) to access Magento APIs without knowing user credentials. Instead, the application receives tokens with specific permissions (scopes).
In Magento, an OAuth “integration” defines which resources the external app can access:
- Integration is created in the Magento Admin.
- Magento generates a consumer key and consumer secret.
- The integration performs an OAuth “handshake” to receive request and access tokens.
OAuth Flow Overview
- Merchant creates an integration in Admin.
- Magento generates consumer key and consumer secret.
- External app receives activation data (callback + identity link).
- App requests a request token via
/oauth/token/request. - App exchanges request token for an access token via
/oauth/token/access. - App calls Magento REST endpoints using OAuth headers.
Example: Request Token via cURL
curl -X POST "https://your-domain.com/oauth/token/request" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "oauth_consumer_key=<consumer_key>&oauth_nonce=<nonce>&oauth_signature_method=HMAC-SHA1&oauth_signature=<signature>&oauth_timestamp=<timestamp>&oauth_version=1.0"
Response example:
oauth_token=<request_token>&oauth_token_secret=<request_token_secret>
Using the Access Token
Once you receive an oauth_token and oauth_token_secret, sign your REST
calls with OAuth 1.0a parameters in the Authorization header.
Best use cases for OAuth:
- Long-living integrations (ERP, CRM, middleware).
- Apps where you don’t want to store Magento usernames/passwords.
- Fine-grained access where each integration is restricted by ACL resources.
3. Session-Based Authentication
What Is Session-Based Authentication?
Session-based authentication uses the existing Magento login session (customer or admin) to authorize API access. The web API framework checks the logged-in session and grants access to resources that are allowed for that user.
- Customer session: Used in storefront context (e.g., JS widgets).
- Admin session: Used inside the Admin area (but not for all API endpoints).
Example customer endpoint:
GET /rest/V1/customers/me
Example: JavaScript Fetch with Customer Session
If a customer is logged into the storefront, you can call APIs from JavaScript and rely on their session cookie:
<script>
fetch('/rest/V1/customers/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include' // send session cookies
})
.then(response => response.json())
.then(data => {
console.log('Logged-in customer:', data);
})
.catch(error => console.error('Error:', error));
</script>
Notes:
- Session-based authentication is ideal for in-storefront AJAX widgets.
- Admin session-based authentication is not supported for general API clients.
- Always protect sessions with HTTPS and secure cookie flags.
Additional Security Best Practices for Magento 2 APIs
- Force HTTPS: Configure your web server and Magento base URLs to use HTTPS only.
- Limit API roles: Create dedicated API roles with minimum required permissions.
- IP whitelisting: Restrict access to admin APIs from specific IP ranges if possible.
- Rate limiting: Apply rate limits via firewall, reverse proxy, or WAF to mitigate abuse.
- Rotate keys and tokens: Periodically regenerate OAuth consumer keys and revoke unused tokens.
- Monitor logs: Regularly monitor
var/log/for suspicious API activity. - Keep Magento updated: Apply security patches and upgrade Magento to supported versions.
Conclusion
Securing the Magento 2 API is essential to protect your store, your customers, and your data. Magento provides three authentication mechanisms—Token-based, OAuth-based, and Session-based—that you can choose from depending on your use case.
By combining strong authentication, robust ACL configuration, HTTPS, rate limiting, and continuous monitoring, you can significantly reduce the risk of unauthorized access and data breaches. Treat API security as an ongoing process: review your integrations regularly, remove unused tokens and integrations, and keep your Magento environment up-to-date.
Implement these techniques in your codebase and APIs to build a secure, scalable, and trustworthy Magento 2 platform for your business and your customers.