# Authentication

Every Liana API uses the same OAuth 2.0 client credentials flow. You create credentials for an
application in LianaAccount, exchange them for an access token, and send the token with each
request.

<ol className="liana-flow not-prose">
  <li><span>1 · LianaAccount</span><strong>Create credentials</strong>Client ID and secret for one application</li>
  <li><span>2 · tokens.lianacloud.com</span><strong>Request a token</strong>Access token, valid 15 minutes</li>
  <li><span>3 · Liana API</span><strong>Call the API</strong>Authorization: Bearer token</li>
</ol>

## Create API credentials

1. Log in to [LianaAccount](https://account.lianacloud.com/) and open the application.
1. Open the **API credentials** tab.
1. Create credentials. Give them a name, and an expiry date if you want them to stop working on a
   set date.
1. Copy the client ID and secret. **The secret is shown only once**, so store it safely before you
   close the dialog.

:::note{title="Who can create credentials"}

Organization admins can create, rotate and delete credentials. Other users can see them but not
change them. If you're not an admin, ask your organization's admin.

:::

:::note{title="One application, one product"}

Credentials work with the application they were created for. A token for one product is rejected by
the others, so create credentials for each product you use.

:::

Where credentials are available:

| Product         | Availability                                                                                                                                                                                          |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LianaMailer     | All installations                                                                                                                                                                                     |
| LianaAutomation | Installations on automation.lianacloud.com                                                                                                                                                            |
| LianaMonitor    | When the API add-on is enabled                                                                                                                                                                        |
| LianaCommerce   | All shops, from January 2027                                                                                                                                                                          |
| LianaCMS        | From January 2027, sites whose admins sign in through LianaCloud, which not every site does. Credentials belong to the user who creates them: see [LianaCMS authorization](/cms/guide/authorization). |

LianaCommerce and LianaCMS accept Bearer tokens from their January 2027 updates. Until then, use a
[shop API key](/commerce/guide/authorization#api-key) or a
[CMS API token](/cms/guide/authorization#cms-api-token). Both keep working after the updates too.

## Request an access token

Make an OAuth 2.0 client credentials request to

<CopyCode value="https://tokens.lianacloud.com/token" />.

`scope` is optional. Without it, the token gets every scope your credentials have. With it, the
token gets only the scopes you ask for, and each of them must belong to the credentials.

LianaAccount gives each credential the product's scope and its `:read`, `:write` and `:delete`
sub-scopes:

| Product         | Scopes                                                                                   |
| --------------- | ---------------------------------------------------------------------------------------- |
| LianaMailer     | `mailer-api`, `mailer-api:read`, `mailer-api:write`, `mailer-api:delete`                 |
| LianaAutomation | `automation-api`, `automation-api:read`, `automation-api:write`, `automation-api:delete` |
| LianaMonitor    | `monitor-api`, `monitor-api:read`, `monitor-api:write`, `monitor-api:delete`             |
| LianaCommerce   | `commerce-api`, `commerce-api:read`, `commerce-api:write`, `commerce-api:delete`         |
| LianaCMS        | `cms-api`, `cms-api:read`, `cms-api:write`, `cms-api:delete`                             |

LianaAutomation, LianaCommerce and LianaCMS limit calls by sub-scope; their
[LianaAutomation](/automation/guide/authorization),
[LianaCommerce](/commerce/guide/authorization#bearer-token) and
[LianaCMS](/cms/guide/authorization#scopes) authorization guides list what each needs.
LianaMailer doesn't check the sub-scopes yet, so they have no effect
there. The examples request the product's scope, which works the same as leaving `scope` out.

```bash title="cURL"
curl -X POST https://tokens.lianacloud.com/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=<client_id>" \
  -d "client_secret=<client_secret>" \
  -d "scope=mailer-api"
```

The token is in `access_token`. `expires_in` is in seconds.

```json title="Response"
{
  "access_token": "<token_string>",
  "expires_in": 900,
  "scope": "mailer-api",
  "token_type": "Bearer"
}
```

:::tip{title="Reuse the token"}

Tokens are meant to be cached and reused across requests until they expire. You can request a new
token at any time, but avoid requesting one per call: the token endpoint is rate-limited per client
ID, so requesting a token for every call fails under load.

:::

## Call the API

Send the token in the `Authorization` header of every request.

```http title="Header"
Authorization: Bearer <token_string>
```

Your application's API URL and the token URL are shown in LianaAccount, below your credentials.
The LianaCommerce API URL is the shop's address followed by `/api/v1`; see
[API URL](/commerce/guide/introduction#api-url).

## Manage credentials

In [LianaAccount](https://account.lianacloud.com/), admins can manage the credentials of each
application.

| Action      | What it does                                                                                                                |
| ----------- | --------------------------------------------------------------------------------------------------------------------------- |
| Rotate      | Creates a new secret. The old secret stops working immediately. Tokens already issued work until they expire.               |
| Expiry date | Optional, set when you create the credentials. After that date, token requests fail.                                        |
| Delete      | Removes the credentials. Integrations that use them can no longer get tokens. Tokens already issued work until they expire. |
| Last used   | Shows when each set was last used to request a token, so you can find and remove unused credentials.                        |

:::warning{title="Keep the secret on your server"}

Store it in a secret manager or an environment variable. Never put it in browser code, a mobile app
or a code repository. If it leaks, rotate it.

:::

## Errors

### Token request

The token endpoint returns the same errors for every product.

| What happened                                     | Response                  | What to do                                                                                                            |
| ------------------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Wrong client ID or secret, or expired credentials | `401 invalid_client`      | Check the values. If the credentials have expired, create new ones. If the secret is lost, rotate it in LianaAccount. |
| Scope that the credentials don't have             | `400 invalid_scope`       | Request only scopes the credentials have, or leave `scope` out.                                                       |
| Too many token requests                           | `429 rate_limit_exceeded` | Wait and try again. Cache the token and reuse it across requests instead of requesting one per call.                  |

### API calls

How an API rejects a missing or invalid token depends on the product:

| Product               | Response                                                                                                                                                                                                                                                                 |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| LianaMailer v1 and v2 | Missing or malformed header: HTTP status 404. Invalid or expired token: HTTP status 200 with `succeed: false` and a message that starts with `Unauthorized`. Token for another product: HTTP status 200 with `succeed: false` and a generic message with an incident ID. |
| LianaMailer v3        | Missing header, or one that is not a Bearer token: HTTP status 400, not JSON. Failed authentication, for example an expired token: HTTP status 401.                                                                                                                      |
| LianaAutomation       | HTTP status 401 for a missing or invalid header, an expired token or a token for another product.                                                                                                                                                                        |
| LianaCommerce         | HTTP status 401 for a missing header. HTTP status 401 with `WWW-Authenticate: Bearer error="invalid_token"` for a malformed or expired token, or a token for another shop or product.                                                                                    |
| LianaCMS              | No header: HTTP status 401. Invalid or expired token, or a token for another site: HTTP status 401 with `WWW-Authenticate: Bearer error="invalid_token"`. Token without the scope for the method: HTTP status 403.                                                       |

If the header is missing or malformed, send `Bearer <token>`. If the token has expired, request a
new one. If it is for another product, request a token with that product's scope and credentials.

For the other errors of each API, see [LianaMailer errors](/mailer/guide/errors), LianaAutomation
[requests and responses](/automation/guide/introduction#requests-and-responses), LianaCommerce
[requests and responses](/commerce/guide/introduction#requests-and-responses) and LianaCMS
[errors](/cms/guide/introduction#errors).
