How to Add User Authentication in Magento
Tags: programming, react
Published: 2021-12-30 15:22:51

# **How to Add User Authentication in Magento**

Before using the API, the system will ask you to authenticate. Why do you need user authentication in Magento? It helps to protect data from unwanted third-party users.

Authentication allows Magento to determine the caller’s user type and the rights to access API requests. We make sure that the user has the required privileges, for example, to edit the product catalog or configure any other feature on your website or [Magento headless commerce solution](https://onilab.com/blog/magento-headless-commerce-explained/).

In this post, I’ll go through the Magento 2 API [authentication process](https://dev.to/propelauth/understanding-user-authentication-from-scratch-3pl2). I will talk about Token, OAuth, and Session Authentication. But before we start, I’ll introduce you to Magento.


## **Short Introduction to Magento**

Magento is an eCommerce engine aiding medium-sized and large online businesses in the creation of a distinctive shopping experience.

Magento is a PHP-based open-source platform currently owned by Adobe. It means you can change and customize it to meet your specific requirements. This platform stands out because of its flexibility in terms of custom development and idea feasibility.

However, it lacks a built-in visual editor, making it difficult for newbies. Because Magento is a platform for expert users, you’ll almost certainly need to employ a Magento development service provider to get a store up and operating.

Managing a store isn’t difficult. When you put everything up, you can add new categories, pages, and products, as well as change them directly in the admin panel. You may use it to manage add-ons, create templates, and much more.

You can download and configure Magento’s Open Source edition for free, which is the choice for [83% of Magento stores](https://litextension.com/blog/magento-2-review/). However, if you require more advanced features, you can upgrade to paid Magento Commerce edition or Magento Commerce Cloud.

Magento is a powerful solution for large businesses with a high volume of visitors and a high turnover.

For example, Magento Commerce can handle 350 million catalog views and 487,000 orders daily. Ahmad Tea, Nestle Nespresso, Land Rover, and other well-known and high-traffic online Magento stores are just a few examples.


## **Defining XML Elements and Attributes**

Where can you establish web API resources and associated permissions in Magento? There is the `webapi.xml` configuration file. This file is used to register our API routes and specify the rights, such as:



* indicating the URL;
* the method (`GET`, `POST`, `SAVE`, and so on);
* interface, where our processes are registered;
* resources, i.e., who has access to the API (`anonymous`, `self`);
* etc.

The table below shows the resources each user type can reach:


<table>
  <tr>
   <td><strong>Type of User</strong>
   </td>
   <td><strong>Available Resources</strong>
   </td>
  </tr>
  <tr>
   <td>Administrator or Integration
   </td>
   <td>Resources with admin or integrator authorization. Suppose administrators are entitled to the <code>Magento_Customer::manage</code> resource. It means they can make a <code>PUT /V1/customers/:customerId</code> call.
   </td>
  </tr>
  <tr>
   <td>Customer
   </td>
   <td>Access to resources with <code>anonymous</code> or <code>self </code>permission
   </td>
  </tr>
  <tr>
   <td>Guest user
   </td>
   <td><code>anonymous </code>permission
   </td>
  </tr>
</table>



## **Steps to Add User Authentication in Magento**

There are three types of authentication in Magento: Token, OAuth, and Session authentication. Token and OAuth are roughly the same things. But for OAuth, you need to log in first and receive an access token for your account.

Or you can simply create a token that will have certain rights and doesn’t [require authorization](https://dev.to/ubahthebuilder/user-authentication-vs-user-authorization-what-do-they-mean-in-back-end-web-development-18bb) with Token Authentication. Each subsection below will tell you how to configure them in steps.


### **1. Token Authentication**

Token-based authentication is preferable for registered users making web API calls using a **mobile application**. What is a token? It’s an electronic key for accessing API(s).



1. A registered user requests** a token** from the token service at the endpoint. Note that this endpoint should be defined for your user type.
2. Once the token service receives a Magento account username and password, it returns a unique **authentication token**.
3. Insert this token in the `Authorization` request header as proof of your identity on web API calls.

There are three types of access tokens by Magento, which differ in terms of longevity: 



1. **Integration \
**It** **doesn’t have time restrictions, and the access granted by the merchant lasts forever **until it is manually revoked**. \

2. **Admin** \
The merchant determines an admin user’s access to Magento resources, lasting **four hours**. \

3. **Customer \
**Such** **tokens are valid for **one hour**. Users with `anonymous `or `self `authorization get access to resources from Magento. These options are not editable by merchants.

Since the token is only valid for a while, we need to ask for it again when it expires.


#### **Step 1. Integration Tokens**

What happens when a merchant creates and activates an integration? Magento generates the following credentials:



* consumer key;
* consumer secret;
* access token;
* access token secret.

All of them are also relevant for OAuth-based authentication, but **Token-based authentication** simply requires the **access token**, and that’s how you can create it:



1. Access the Integrations page. Log in to Admin and go to **System **> **Extensions **> **Integrations**. \

2. To access the New Integration page, click **Add New Integration**. \

3. Proceed to the **Name **field and give the integration a unique name. Type your admin password in the **Your Password** section. Don’t fill in other fields. \

4. Navigate to the **API tab**, where you can choose the access to Magento resources for the integration (all resources or a custom list). \

5. After saving your modifications by clicking the **Save **button, return to the Integrations page. \

6. Find the grid of the newly-created integration, click the **Activate **link, and select **Allow**.

You will see a dialogue like this:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbnqegoy7xknoex805bo.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1pc0i231rzt9xdcgbmb0.png)

The access token can be used for any calls performed by the integration.


#### **Step 2. Admin and Customer Access Tokens**

Administrators and customers each have their own token service in Magento. When you ask one of these services for a token, you’ll receive a unique access token in exchange for your Magento account’s username and password.

Guest users can access resources defined with the `anonymous `permission level using the Magento web API architecture.

Who are guest users? These are users who can’t be authenticated using the framework’s existing authentication procedures. They don’t need to specify a token in a web [API call](https://dev.to/endymion1818/how-to-test-javascript-api-calls-187k) for a resource with anonymous authorization, but they can.

Magento admins must be sure to authenticate using **two-factor authentication**. General users don’t need it, so they have a different authorization API. You can realize your APIs for authorization or enable authorization through a third-party service, such as:



* Duo Security;
* Google Authenticator;
* U2F;
* Authy.

Customer calls for REST and SOAP will look the following way:



* REST: `POST /V1/integration/customer/token`
* SOAP: `integrationCustomerTokenServiceV1`

Include this token in the `Authorization` request header with the `Bearer `HTTP authorization scheme to establish your identity. As I’ve mentioned, an admin token is valid for four hours by default, while a customer token remains operative for one hour. You can change the default settings from the Admin menu like this: 

Select **Stores **> **Settings **> **Configuration **> **Services **> **OAuth **> **Access Token Expiration**

All expired tokens are removed by a cron job that runs every hour.


#### **Step 3. Inquire a Token**

A request for an access token has three essential components:



* **Endpoint** \
It combines the server making the request, the web service, and the `resource `to which the request is addressed. \
 \
Let’s take this endpoint as an example: \
`POST &lt;host>/rest/&lt;store_code>/V1/integration/customer/token`. \
Here, the server is `magento.host/index.php/`, the web service is `rest`, and the resource is `/V1/integration/customer/token`.` \
`
* **Content type**

    It concerns the request body. There are two options to set this value: `"Content-Type:application/json"` or `"Content-Type:application/xml"`. \


* **Credentials** \
This is a Magento account’s username and password. Include code in the call to specify these credentials in a JSON request body: `{"username":"&lt;USER-NAME>;", "password":"&lt;PASSWORD>"}`. \
 \
If you need to indicate these credentials in XML, use this code in the call: `&lt;login>&lt;username>customer1&lt;/username>&lt;password>customer1pw&lt;/password>&lt;/login>`.

Here’s an example of the `curl `command to request a token for an admin account:


```
curl -H "Content-Type: application/json" \
--request "POST" \
--data '{"username":"<username>","password":"<password>"}' \
https://<magento_host>/index.php/rest/V1/integration/admin/token
```



#### **Step 4. Authentication Token Response**

The response body with the token will look like this, provided the request is successful:


```
6yivz6jrmo147x4skq0xt1ights6siob
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7uiwbgxok9f6gdsu3t0.png)

#### **Step 5. Utilizing the Token in a Web API Call**

You need the authentication token when you access the resource that requires a permission level higher than “anonymous”. Include it in the header of any web API call, using the following HTTP header format:


```
Authorization: Bearer <authentication token>
```


**a) Admin Access**

Admins have full access to all resources for which they received permission. Here is how you perform a web API call with an admin token:


```
curl -X GET https://<magento_host>/index.php/rest/V1/customers/29171 \ 
-H "Authorization: Bearer 6yivz6jrmo147x4skq0xt1ights6siob"
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytm0nfy4qhwk6pb3ery8.png)

**b) Customer Access**

Unlike admins, customers can’t access all resources other than with `self` permissions. The following code explains how to use a customer token to make a web API call:


```
curl -X GET https://<magento_host>/index.php/rest/V1/customers/me \ 
-H "Authorization: Bearer 6yivz6jrmo147x4skq0xt1ights6siob"
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akqjqnlsjl41e2leyror.png)

### **2. OAuth Authentication**

Let’s talk about the Magento OAuth authentication process. This type of authentication is based on OAuth 1.0a, a secure API authentication open standard. OAuth is a token-passing technique to specify access for **third-party applications** to internal data. It’s done without revealing or storing user IDs or passwords.

Such a third-party application using OAuth for authentication is known as **integration **in Magento. OAuth authentication determines the resources that the application can access. For example, you can enable all resources or restrict the list.

To illustrate my point, suppose you use Mailchimp to notify your store visitors about the abandoned carts. When a visitor leaves your website with an unpaid order, Mailchimp needs to obtain a list of such clients, the contents of their carts, and email addresses. As a store owner, you specify the Mailchimp rights with the help of OAuth authentication.

That’s how Magento generates the tokens needed for authentication:



1. It starts by generating a **request token**. \

2. This token is usable for a short time and must be exchanged for an **access token**.

    Access tokens have a lengthy lifespan and expire only when the merchant revokes the application access.



#### **Step 1. OAuth Overview**

The OAuth authentication process takes ten steps:



1. **Creating an integration** from Admin. The merchant builds an integration, while Magento generates a **consumer key** and a **consumer secret**. \

2. The next step is **activating the integration**, which starts the OAuth process. Magento uses HTTPS post to transmit the following attributes to the external application: \

    1. OAuth consumer key and secret;
    2. OAuth verifier;
    3. the store URL. 

    These credentials go to the page indicated in the Callback Link field in Admin.

3. The integrator **receives the activation information** and saves it to ask for tokens. \

4. Magento **accesses the application login page** specified in the Admin Identity Link field. \

5. The merchant **logs in to the third-party application**, which will integrate with Magento. The application returns to the call location in case of a successful login. The login page doesn’t participate in this process. \

6. The application **asks for a request token**. It uses the REST API `POST /oauth/token/request`. The consumer key and other details are included in the `Authorization `header. \

7. The application** receives a request token and a request token secret** from Magento. \

8. The application **asks for an access token** using the REST API `POST /oauth/token/access`. The request token and other details are included in the `Authorization `header. \

9. Magento **delivers an access token and an** **access token secret **if the request is successful. \

10. The application **can operate the store resources**. All requests submitted to Magento must include the entire set of request parameters in the `Authorization `header.


#### **Step 2. Activating Integration**

How can you configure integration? Go to the Admin **System** > **Extensions **> **Integrations**. The process also involves a callback URL and an identity link URL.

What is a **callback URL**? This link specifies where OAuth credentials can be transmitted during OAuth token exchange. On the other hand, the identity link takes you to the login page of the external application, which will integrate with Magento.

When merchants create an integration, they can select **Save and Activate**. Or the merchant can use the **Activate **button to activate a previously saved integration from the Integration grid.

Magento creates a consumer key and a consumer secret after initiating the integration. When you activate an integration, it sends the [credentials to the endpoint](https://dev.to/ebereplenty/react-authentication-protecting-and-accessing-routes-endpoints-96h) you specified when you created it. 

The following attributes will be in an HTTP POST from Magento to the Integration endpoint:



* `store_base_url` (for example, http://magento-store-example.com);
* `oauth_verifier`;
* `oauth_consumer_key`;
* `oauth_consumer_secret`.

To receive a request token, integrations utilize the key: `oauth_consumer_key`. And to get an access token, they use the `oauth_verifier`.


#### **Step 3. OAuth Handshake Details**

To complete a two-legged OAuth handshake, you must obtain:



* a request token;
* an access token.

**a) Getting a Request Token**

A request token is a one-time usage token needed to exchange for an access token. This API allows you to obtain a request token from Magento:


```
POST /oauth/token/request
```


These request parameters must be included in the `Authorization `header of the call:



* `oauth_consumer_key`;
* `oauth_signature_method`;
* `oauth_signature`;
* `oauth_nonce`;
* `oauth_timestamp`;
* `oauth_version`.

Fields in the response include:



* `oauth_token`, the token to request an access token;
* `oauth_token_secret`, a secret value that identifies who owns the token.

An example of a valid response may look:


```
oauth_token=6rq0x917xdzkhjlru0n4m2r6z2vvj66r&oauth_token_secret=4d85786q9yxisfjoh0d2xgvsard8j0zj
```


**b) Acquiring an Access Token**

Integrators obtain an access token in exchange for the request token, using the following API:


```
POST /oauth/token/access
```


The call `Authorization` header contains the same request parameters as for the request token, plus:



* `oauth_token`, or the request token;
* `oauth_verifier`, a verification code transmitted as part of the initial POST transaction.

Here’s an example of a valid response:


```
oauth_token=6rdpi1d4qypjpcdxcktef35kmmqxw6b1&oauth_token_secret=fcufgnt83chiljiftg2uj7nty6vvfzgo
```


It includes the following fields:



* `oauth_token`, which enables third-party applications to access protected resources;
* `oauth_token_secret`.


#### **Step 4. Access Web APIs**

Third-party applications, or integrators, can use the access token to make Magento web APIs, such as:


```
GET /rest/V1/addresses/3112
```


The request parameters in the `Authorization` request header in the call must be:



* `oauth_consumer_key`;
* `oauth_nonce`;
* `oauth_signature_method`;
* `oauth_signature`;
* `oauth_timestamp`;
* `oauth_token`.


#### **Step 5. The OAuth Signature**

`Authorization `header includes the signature of every OAuth handshake and Web API requests. How do you generate the OAuth signature? The signature base string is created by connecting the following set of URL-encoded attributes and parameters with the ampersand (&) character:



* HTTP method;
* URL;
* `oauth_nonce`;
* `oauth_signature_method`;
* `oauth_timestamp`;
* `oauth_version`;
* `oauth_consumer_key`;
* `oauth_token`.

The signature generation requires the HMAC-SHA1 signature method. Even if the consumer secret and token secret are both empty, the signing key is the sequence of their values separated by the ampersand (&) character (ASCII code 38). Each value must be encoded using parameter encoding.


### **3. Session Authentication**

Users may be required to confirm their identity every time they want to make a call. Sessions let them avoid this repetitive task. When a person logs in, their temporary session is created, which stores data. And then, the data for verification is taken from the session where authorization is required.

The **JavaScript widget on the Magento storefront or Admin** is the preferred client for session-based authentication.

How does this authentication work? A cookie identifies a session of a registered user, which expires after a period of inactivity. You can also use the system as a guest user without logging in.

Depending on the type of user, you log in to the Magento store with customer or administrator credentials. The Magento web API framework recognizes you and controls what resources you’re trying to access.

Suppose a customer logs in, and the JavaScript widget calls the `self `API, the following method retrieves the details:

`GET /rest/V1/customers/me`.

Note that API endpoints don’t support admin session-based authentication at this time. AJAX calls are the only way to use session-based authentication. Due to security flaws, direct browser requests are not possible. A developer can make a custom Magento widget to send requests without requiring any further authentication.


## **To Sum Up**

This article covered three types of Magento authentication: 



* Token;
* OAuth;
* Session.

Each one has a preferred type of user, so you need to know how to add them in steps. If you want to give access to the resources for customers, admins (integrations), or guest users, you configure permission in the `webapi.xml` file.

Why do you need it all? It is needed for security so that no user can access your data or make changes in the online store without your permission.