To authenticate the API, we can pass the admin token, customer token, or integration token along with the API request in Magento 2. This type of authentication process is called Token-based authentication.
Introduction to Magento 2 API and different types of API authentication mechanism used in Magento 2 are present in my previous article.
In token-based authentication, we need to pass an admin token to access the resources of the admin user. In this article, we will be looking into how we can get the admin token in Magento 2.
NOTE:
- Admin token is valid for 4 hours by default.
- This value can be changed from Magento admin: STORES > Settings > Configuration > Services > OAuth > Access Token Expiration > Admin Token Lifetime (hours).
- A cron job that runs hourly removes all expired tokens.
Get Admin Token (when 2FA is disabled)
Get admin token when two-factor authentication is disabled.
API Doc:
https://adobe-commerce.redoc.ly/2.4.5-admin/tag/integrationadmintoken
Endpoint:
POST <host>/rest/V1/integration/admin/token
Headers:
Content-Type application/json
Payload:
{
"username": "admin",
"password": "<admin-password>"
}
Response:
Magento generates the admin’s access token
djo1z1qgghnxxxxxjbha0jrssqkkmef8
Get admin token using cURL Request
curl --location --request POST '<host>/rest/V1/integration/admin/token' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "<admin-username>",
"password": "<admin-password>"
}'
NOTE:
If you have 2FA (Magento_TwoFactorAuth module) enabled and you try to POST to the endpoint <host>/rest/V1/integration/admin/token
, then you will receive response similar to the following:
{
"message": "Please use the 2fa provider-specific endpoints to obtain a token.",
"parameters": {
"active_providers": [
"google"
]
}
}
Get Admin Token (when 2FA is enabled)
Get admin token when two-factor authentication is enabled.
Different two-factor authentication providers can be used for admin users’ 2FA in Magento.
Below is the list of different two-factor authentication providers in Magento along with their REST API endpoints.
Admin with Google Authenticator POST /V1/tfa/provider/google/authenticate
Admin with Duo Security POST /V1/tfa/provider/duo-security/authenticate
Admin with Authy. POST /V1/tfa/provider/authy/authenticate
Admin with U2F POST /V1/tfa/provider/u2fkey/verify
In the examples below, I will be using Google Authenticator as Magento’s 2FA provider.
API Doc:
https://adobe-commerce.redoc.ly/2.4.5-admin/tag/tfaprovidergoogleauthenticate
Endpoint:
You can specify the store_code
POST <host>/rest/<store_code>/V1/tfa/provider/google/authenticate
Or, you can also call the API without the store_code
, which will auto-pick the default store code.
POST <host>/rest/V1/tfa/provider/google/authenticate
Headers:
Content-Type application/json
Payload:
{
"username": "<admin-username>",
"password": "<admin-password>",
"otp": "<otp-value>"
}
Response:
Commerce generates the admin’s access token
djo1z1qgghnbc0gfjbha0jrssqkkmef8
Get admin token using cURL Request
curl --location --request POST 'https://<host>/rest/V1/tfa/provider/google/authenticate' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "<admin-username>",
"password": "<admin-password>",
"otp": "<6-digit-otp-code>"
}'
Get admin token using PHP-cURL
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://<host>/rest/V1/tfa/provider/google/authenticate',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"username": "<admin-username>",
"password": "<admin-password>",
"otp": "<6-digit-otp-code>"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Get admin token using PHP-Guzzle
<?php
$client = new Client();
$headers = [
'Content-Type' => 'application/json'
];
$body = '{
"username": "<admin-username>",
"password": "<admin-password>",
"otp": "<6-digit-otp-code>"
}';
$request = new Request('POST', 'https://<host>/rest/V1/tfa/provider/google/authenticate', $headers, $body);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
Get admin token using Node.js Request
var request = require('request');
var options = {
'method': 'POST',
'url': '<host>/rest/V1/tfa/provider/google/authenticate',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"username": "<admin-username>",
"password": "<admin-password>",
"otp": "<6 digit otp code>"
})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Use Admin Token to Access Any Customer Data
If the admin user is given customer resource access, then the admin token generated above can be used to access data of any customer in Magento.
API Doc:
https://adobe-commerce.redoc.ly/2.4.5-admin/tag/customerscustomerId
Endpoint:
Accessing customer with ID = 2
With store_code
GET <host>/rest/<store_code>/V1/customers/2
Or, without store_code
GET <host>/rest/V1/customers/2
Headers:
Content-Type application/json
Authentication Bearer Token:
<admin-token-generated-above>
Get customer data using cURL Request
curl --location --request GET '<host>/rest/V1/customers/2' \
--header 'Authorization: Bearer djo1z1qgghnbc0gfjbha0jrssqkkmef8'
Hope this helps. Thanks.
References: