> For the complete documentation index, see [llms.txt](https://devcenter.unico.io/you/Ol1H6eGO4sQvPYB1Nmyl/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://devcenter.unico.io/you/Ol1H6eGO4sQvPYB1Nmyl/authentication/obtaining-credentials.md).

# Obtaining credentials

Authentication on the Unico IDCloud platform uses the OAuth2 protocol, in the Two-Legged OAuth (2LO) model.

* It is done through a service account, linked to the application (not to a user).
* The application calls the Unico APIs on behalf of the service account.
* This is the ideal scenario for server-to-server interactions.

## Service Account Request <a href="#solicitacao-da-conta-de-servico" id="solicitacao-da-conta-de-servico"></a>

To create the service account, send the following to your company's project manager:

* Name of the service account to be created (up to 12 characters).
* Name, email, and cell phone of the person responsible for the service account.
  * The cell phone must be Brazilian, American, or Mexican.

{% hint style="warning" %}
UAT and Production require distinct accounts.
{% endhint %}

After the data is sent, the service account will be created, and you will receive an email to generate the private key (.PEM). The service account includes:

* Unique account name.
* Tenant ID (company identifier).
* The base payload to build the JWT.
* Private key (.PEM) - the browser will download this automatically at the end of the service account generation, and it will be available in your computer's downloads folder.

> :bulb:Check your SPAM folder if you do not find the email for generating the service account.

{% hint style="success" %}
If you need the public key, request it from the project manager or generate it via OpenSSL:

```
openssl req -x509 -new -nodes -sha256 -days 720 \
-key fileName.key.pem -out fileName.cert.pem
```

{% endhint %}

## Authentication Flow <a href="#fluxo-de-autenticacao" id="fluxo-de-autenticacao"></a>

Your application must follow 4 steps:

1. Create the JWT (header + payload + signature).
2. Request the access token (access-token) from the authentication platform.
3. Handle the response (store and use the access-token in API calls).
4. Access token validity.

### 1. Creating the JWT <a href="#criando-o-jwt" id="criando-o-jwt"></a>

#### 1.1 **Structure**

A JWT has 3 parts concatenated by `.`:

```
{Header Base64url}.{Payload Base64url}.{Signature Base64url}
```

#### 1.2 Header

```json
{"alg":"RS256","typ":"JWT"}
```

Base64url:

```
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
```

#### 1.3 Payload&#x20;

```json
{
  "iss": "service_account_name@tenant_id.iam.acesso.io",
  "aud": "https://identityhomolog.acesso.io",
  "scope": "*",
  "iat": 1626293376,
  "exp": 1626296976
}
```

<table><thead><tr><th width="172.6666259765625">Name</th><th>Description</th></tr></thead><tbody><tr><td><code>iss</code></td><td>Identifier of the service account (Service Account). The pattern is: account name + @ + Tenant ID + iam.acesso.io. (e.g., "<code>service_account_name@tenant_id.iam.acesso.io</code>").</td></tr><tr><td><code>scope</code></td><td>Requested permissions. Use "<code>*</code>" for all.</td></tr><tr><td><code>aud</code></td><td>Always <code>https://identityhomolog.acesso.io</code> for UAT or <code>https://identity.acesso.io</code> for Production (⚠️ <em>without a trailing slash and always with HTTPS</em>).</td></tr><tr><td><code>iat</code></td><td>JWT issuance time, in seconds (<em>in Unix Timestamp standard</em>).</td></tr><tr><td><code>exp</code></td><td>Token expiration in seconds (max. +3600s relative to <code>iat</code>). This value cannot be fixed and has a maximum time of 1 hour after the JWT issuance time.</td></tr></tbody></table>

Example calculation:

```
exp = iat + 3600
```

#### 1.4 Signature

* Algorithm: **RS256 (*****RSA + SHA-256*****)**.
* Input: `{Header Base64url}.{Payload Base64url}`.
* Signature made with the private key (`.key.pem`).

Final result: `{Header Base64url}.{Payload Base64url}.{Signature Base64url}`

Below is an example of a JWT token before Base64url encoding:

```json
{"alg":"RS256","typ":"JWT"}.
{
  "iss": "service_account_name@tenant_id.iam.acesso.io",
  "aud": "https://identityhomolog.acesso.io",
  "scope": "*",
  "exp": 1626296976, // This is an example
  "iat": 1626293376 // EThis is an example
}.
[byte array of the signature]
```

### 2. Requesting the Access Token <a href="#solicitando-o-token-de-acesso" id="solicitando-o-token-de-acesso"></a>

Send the signed JWT to the platform:

**POST Endpoint:**

* **UAT**: `https://identityhomolog.acesso.io/oauth2/token`.
* **PROD**: `https://identity.acesso.io/oauth2/token`.

**Headers:**

```
Content-Type: application/x-www-form-urlencoded
```

**Body:**

<table><thead><tr><th width="160.666748046875">Name</th><th>Description</th></tr></thead><tbody><tr><td>grant_type</td><td>grant_type Use the following text, URL-encoded if necessary: <code>urn:ietf:params:oauth:grant-type:jwt-bearer</code>.</td></tr><tr><td>assertion</td><td>The JWT, including the signature.</td></tr></tbody></table>

```x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
assertion=<JWT_assinado>
```

Request example:

```http
POST /oauth2/token HTTP/1.1
Host: identityhomolog.acesso.io
Content-Type: application/x-www-form-urlencoded

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-
bearer &
assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzZXJ2aWNlX2FjY
291bnRfbmFtZUB0ZW5hbnRfaWQuaWFtLmFjZXNzby5pbyIsInN1YiI6InVzZXJfaWRlbnRpZmllciIs
ImF1ZCI6Imh0dHBzOi8vaWRlbnRpdHlob21vbG9nLmFjZXNzby5pbyIsInNjb3BlIjoiKiIsImV4cCI
6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ.TjH-mTtwP6tBB93O1sDPaAA6yUF7N2-HZDlpIPz
bf_dxO8A6KZuRWG8ZnICrxX56qj0HREiMlYy27XJgxowrUa0JHvbqc8HJkT7-6Mh7J67UnubZKG1-hi
6jDtkC9BIXBcOhtkNUfZvZetXjLzsRsSDkqxdMtzYZwkRlocvaxL5QXiQhweeEwK_Ux81Adh3z0EIhT
yl7CKJLJ69PuHS7s9IdrjUl79owipp4LF1FvtMhoe7YIL69ohPgFqSv_-Y9qpPdW6be3OEAyKlOM08S
ZBbHBwW4XMvw3uZjTY1sgJ4cBoxrftDpjYOw34oPOKxirqc5-90uOCYe1O1hRtG45w
```

### 3. Handling the Response <a href="#tratando-a-resposta" id="tratando-a-resposta"></a>

Example response from the platform:

```json
{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "expires_in": "3600"
}
```

* Use the `access_token` in all calls to the Unico APIs.
* If an error is returned, validate:
  * JWT is correctly formed.
  * Time defined in `iat` and `exp`.
  * Service account has the necessary permissions.

### 4. Access Token Validity <a href="#validade-do-token-de-acesso" id="validade-do-token-de-acesso"></a>

* The time is informed in `expires_in` (seconds).
* Default: 3600s (1 hour).
* Renew the token when 10 minutes remain before expiration.

Example&#x73;**:**

```
Standard scenario:
expires_in: 3600 (1h) - Token genrated at 14h42

Request a new token only at 15:32, i.e., 14:42 + (3600 - 600)
```

{% hint style="warning" %}
A new access token can be requested when 10 minutes remain before expiration.
{% endhint %}

* ¹ According to RFC 4648 for BaseN encoding, the Base64url format is similar to the Base64 format, with the exception of the `=` character, which must be omitted, and the `+` and `/` characters, which must be replaced by `-` and `_`, respectively.
* ² JSON Web Signature: <https://tools.ietf.org/html/rfc7515>.
