# Token Acquisition

The authentication method used for invoking the APIs is "Bearer." To obtain the application-type token required for this purpose, you need to call the Auth Manager service. The endpoint to use is as follows, where BASE\_URL represents the domain of the current project:&#x20;

```
POST https://{BASE_URL}/am/apif/oauth/application-token
```

For example, if the domain of my project is `matdev.40mat.com`, the URL becomes:

```
POST https://matdev.40mat.com/am/apif/oauth/application-token
```

Before invoking the endpoint, ensure that you have the following credentials:

* the name of the application registration for the project;
* Basic authentication credentials for the Auth Manager;
* username and password for the application registration.

If you do not have these credentials, you can request them from the project contact person. Note that the credentials for the application registration can be retrieved by accessing the Microsoft Entra Id service, while the Basic authentication credentials need to be arranged with the person responsible for configuring the MAT services.

Once you have the necessary credentials, you can invoke the endpoint to obtain your Bearer token. The domain to use will be that of the current project, concatenated with the suffix `/am` and the endpoint you want to invoke `/apif/oauth/application-token`. Here is an example URL:

```
https://myProjectName.40mat.com/am/apif/oauth/application-token
```

Below is an explanation of all the parameters necessary for invoking the above-mentioned endpoint.

<details>

<summary>Request</summary>

```
HTTP
POST https://myProjectName.40mat.com/am/apif/oauth/application-token
```

#### Headers

<pre><code><strong>AUTH
</strong>{
    "App-Name" : "yourAppName-be",
    "Authorization" : "Basic yourBase64EncodeOfClientId:ClientSecret"
}
</code></pre>

In the header, you need to specify the following two keys:

* `App-Name`: this is the identifier for the application registration. Note that, according to the conventions followed in all MAT projects, the application registration name should match the project’s App-Name followed by the suffix "*-be*";
* `Authorization`: in this field, you need to provide your Basic token. The string should consist of the word "Basic " (note the intentional space after the word "Basic") followed by your token, which is obtained by encoding your Basic Auth credentials (username and password) in Base64, separated by a colon. Below, a script will be provided for the encoding process.

#### Body

```
JSON

{
  "credentials": {
      "client_id": "your client id code";
      "client_secret": "your client secret word"
  }
}
```

The body must contain:&#x20;

* `credentials`: a dictionary containing the following keys:
  * `client_id` : the client ID associated with the application registration;
  * `client_secret` : the client secret associated with the application registration.

</details>

<details>

<summary>Response</summary>

The response you will receive from the Auth Manager will have a format similar to the following and will contain the application token to be used when invoking the APIs.

```json
JSON

{
    "access_token": "eyJ0eXA.............vH70g",
    "expires_at": 1718373652,
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "token_type": "Bearer"
}
```

</details>

***

{% tabs %}
{% tab title="Python" %}
Script for encoding your credentials in Base64 and calculating the Basic token.

```python
import base64

# Assign the values of client_id and client_secret
client_id = 'BasicClientId'
client_secret = 'BasicClientSecret'

# Combine client_id and client_secret separated by ':'
credentials = f"{client_id}:{client_secret}"

# Encode the credentials in Base64
encoded_credentials = base64.b64encode(credentials.encode()).decode()

# Create the Basic authorization header
authorization_header = f"Basic {encoded_credentials}"

# Print the header to verify it
print(authorization_header)
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Python" %}
Script per la richiesta di un token Bearer applicazione all'Auth Manager.

```python
import requests
import json
import base64
 
# Define the URL of the endpoint
url = 'https://yourProjectName.40mat.com/am/apif/oauth/application-token'
 
# Define the values for client ID and client secret
# These credentials are for Basic authentication with the Auth Manager
client_id = 'BasicClientId'
client_secret = 'BasicClientSecret'

# Encode the client ID and client secret in Base64
auth_str = f'{client_id}:{client_secret}'
auth_bytes = auth_str.encode('utf-8')
auth_base64 = base64.b64encode(auth_bytes).decode('utf-8')
 
# Define the request headers
headers = {
    "App-Name": "yourProject-be",
    "Authorization": auth_base64
}
 
# Define the request body (in this case, an empty JSON object)
# These credentials are associated with the application registration
data = {"credentials" : {
    "client_id": "0cxxxxxx-xxxx-xxxx-xxxx-5xxxxxxxxxx5",
    "client_secret": "1xxxxxxqxxxxxxxs.xxxxxxxxxxxx.xx-xxxxxxx"
}}
 
# Make the POST request
response = requests.post(url, headers=headers, data=json.dumps(data))
 
# Check if the request was successful
if response.status_code == 200:
    # Get the data in JSON format
    data = response.json()
    print(data)
else:
    print(f'Request error: {response.status_code}')
    print(response.text)
```

{% endtab %}
{% endtabs %}

## OpenAPI

{% openapi src="<https://content.gitbook.com/content/L65nhvmBlLI1fH4sd9ut/blobs/xMenT125ArqJSbJTI054/openapi3_3%20-%20eng.yaml>" path="/apif/oauth/application-token" method="post" %}
[openapi3\_3 - eng.yaml](https://content.gitbook.com/content/L65nhvmBlLI1fH4sd9ut/blobs/xMenT125ArqJSbJTI054/openapi3_3%20-%20eng.yaml)
{% endopenapi %}

## Token Usage

Once the application token is obtained, it must be used to make all API calls. To do this, you need to construct a header for each call as follows:

```
header = {
    "App-Name" : "yourProjectAppName-be",
    "Authorization": "Bearer ey.....zx1w"
}
```

The keys to include in the header are:

* `App-Name` : the name of the application registration. According to the conventions used in the MAT ecosystem, this name should be constructed from the project’s App-Name followed by the suffix "-be";
* `Authorization` : this key must contain the application token obtained from the invocation of the endpoint [described above](https://40factory.gitbook.io/mat-api-en/authentication/cloud-case/token-acquisition). Note that the token must be preceded by the string "Bearer ", where the space after the word "Bearer" is intentional.

Below is an example in Python for constructing the correct invocation header.

{% tabs %}
{% tab title="Python" %}
Script for Creating an HTTP Request to a Service.

```python
import requests
import json

# Example data for the header
headers = {
    'App-Name': 'yourAppName-be',
    'Authorization': 'Bearer ey....xy1w'
}

# Example data for the body
body = {
    'key1': 'value1',
    'key2': 'value2'
}

# Example data for the query string
query_params = {
    'param1': 'value1',
    'param2': 'value2'
}

# URL of the third-party API
url = 'https://yourDomain/api/endpoint'

# Make the POST request
response = requests.post(url, headers=headers, json=body, params=query_params)

# Check the response status and return the data
if response.status_code == 200:
    print('Success:')
    print(json.dumps(response.json(), indent=4))
else:
    print('Request failed:')
    print(f'Status code: {response.status_code}')
    print(response.text)

```

{% endtab %}
{% endtabs %}
