> For the complete documentation index, see [llms.txt](https://docs.mediarithmics.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mediarithmics.io/setup-and-monitor/manage-the-platform/manage-api-access.md).

# Manage API access

Choose an authentication method, issue tokens and signature keys, and rotate them before they expire.

## Your goal

Give your integrations access to the mediarithmics API with the authentication method that fits where the code runs, and keep track of every credential you have issued so none of them expires unnoticed or outlives its purpose.

## Expected outcome

Server-side integrations authenticate with long-term API tokens borne by service accounts; public applications sign their calls instead of carrying a token; and an administrator can see, at any moment, every credential in the organisation, when it was last used, and when it expires.

{% hint style="danger" %}
Choose the authentication method based on your use case. Choosing the wrong method can lead to significant security risks - access violation, data leakage. A long-term API token embedded in a mobile application can leak by decompiling the application.
{% endhint %}

## Before you start

* A **service account** to bear each production credential, so that deleting a person's account does not cancel a production integration. See [Manage users and roles](/setup-and-monitor/manage-the-platform/manage-users-and-roles.md#the-two-account-types).
* At least one **role** on the account. A user with no role has no access to anything, the API included - see [Manage users and roles](/setup-and-monitor/manage-the-platform/manage-users-and-roles.md#grant-a-role).
* An **organisation administrator** or **community administrator** role, if you intend to manage credentials for the whole organisation rather than only your own.

## Choose the method

| Use case                                                                                   | Method                       |
| ------------------------------------------------------------------------------------------ | ---------------------------- |
| Direct server-to-server integration                                                        | **Long-term API token**      |
| Live data collection from applications - mobile, CTV, anything running on a public network | **Signature authentication** |

The platform is built on an API-first model: essentially anything you can do in the interface or with the tools can be done through the API. The base URL is `https://api.mediarithmics.com`, over HTTPS only - support for HTTP has been discontinued. Make the base URL easy to change in your integration, as it may change in future.

{% hint style="info" %}
Get in touch with your account manager if you want advice on the best authentication method for your needs.
{% endhint %}

## Where credentials live

| Screen                                           | What you do there                                                                                                                        | Who can reach it                           |
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| **Settings > My Account > API Tokens**           | Create and list your own long-term API tokens.                                                                                           | Any user, for their own account.           |
| **Settings > Organisation > API Authentication** | View every API token in the organisation, for user accounts and service accounts alike. Create, edit, and revoke service account tokens. | Community and organisation administrators. |

## Long-term API tokens

A long-term API token identifies a user and has a longer expiration delay than a session - usually **12 to 24 months**. A user can hold several tokens, which is what makes rotation possible without downtime.

{% hint style="info" %}
Create [service accounts](/setup-and-monitor/manage-the-platform/manage-users-and-roles.md#the-two-account-types) to bear long-term API tokens, so that deleting a person's account does not cancel a production token.
{% endhint %}

### Create a token

{% tabs %}
{% tab title="In the interface" %}

1. Open **Navigator**.
2. Go to **Settings**.
3. Open **My Account > API Tokens**.
4. Click **New API Token**.

An administrator creating a token for a **service account** does it from **Settings > Organisation > API Authentication** instead, where service account tokens can also be edited and revoked.
{% endtab %}

{% tab title="By API" %}

```
POST https://api.mediarithmics.com/v1/users/:userId/api_tokens
```

Body: `{ "name": "<the name of the API token>" }`

The response returns the token, including its `value`, `creation_date`, and `expiration_date`.

List the tokens of a user with:

```
GET https://api.mediarithmics.com/v1/users/:userId/api_tokens
```

{% hint style="warning" %}
You need an existing API token to generate a long-term API token through the API. Generate the first one in the Navigator interface.

Listing tokens does not return their complete value.
{% endhint %}
{% endtab %}
{% endtabs %}

### Use the token

Pass the token in the `Authorization` header of every request, with `Content-Type: application/json` on any request carrying a body.

```bash
curl --location --request GET 'https://api.mediarithmics.com/v1/plugins?max_results=100' \
--header 'content-type: application/json' \
--header 'Authorization: <API_TOKEN>'
```

### Govern the tokens you have issued

**Settings > Organisation > API Authentication** is the single dashboard for the credentials of an entire organisation. Administrators use it to:

* **See everything in one place** - all API tokens across the organisation, for both user accounts and service accounts.
* **Manage service accounts without a developer** - create, edit, and revoke service account tokens directly in the interface.
* **Monitor activity** - the **Last Used** date of every token tells you whether an integration is still alive.
* **Anticipate expirations** - track expiration dates so an integration never goes dark because a token silently lapsed.
* **Clean up** - identify zombie tokens that are no longer in use and remove them.

### Rotate a token

Because a user can hold several tokens at once, a rotation never needs a gap in service.

{% stepper %}
{% step %}

### Create the replacement before the old token expires

Issue a second token on the same account. Both are valid at the same time.
{% endstep %}

{% step %}

### Update the integration

Deploy the new value, then let the integration run.
{% endstep %}

{% step %}

### Confirm the old token is idle

Check its **Last Used** date in **API Authentication**. If it stops moving, nothing is calling with it any more.
{% endstep %}

{% step %}

### Revoke the old token

Remove it so it cannot be used again. Service account tokens are revoked from **API Authentication**.
{% endstep %}
{% endstepper %}

## Signature authentication

Signature authentication is for environments where the calling party operates on a public network, or in a published mobile or CTV app - situations where the communication could be intercepted or the app decompiled. It is the preferred choice for [app tracking](/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/app-tracking.md).

The caller is authenticated with a message authentication code computed with `HMAC-SHA256`. Like an API token, a signature key is linked to a mediarithmics user, so create a technical user to bear it.

{% hint style="warning" %}
Signature authentication is limited to two actions:

* Posting activities - `POST /v1/datamarts/${datamart_id}/user_activities`
* Getting user segments by user account ID, email hash, or user agent ID - **not** by UserPoint ID:
  * `GET /v1/datamarts/:datamartId/user_points/compartmentId=:compartmentId,user_account_id=:userAccountId/user_segments`
  * `GET /v1/datamarts/:datamartId/user_points/email_hash=:emailHash/user_segments`
  * `GET /v1/datamarts/:datamartId/user_points/user_agent_id=:userAgentId/user_segments`
    {% endhint %}

### Generate a secret key

```
POST https://api.mediarithmics.com/v1/users/:userId/message_authentication_keys
```

| Request field | Value                                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `scheme`      | `HMAC_SHA256`                                                                                                                              |
| `key_id`      | A unique string identifying your secret key. The API returns an error if the value is already used. You use this value when signing calls. |

The response contains `id`, `user_id`, `creation_ts`, `expiration_ts`, `key_id`, `scheme`, and `secret_key` - a 16-byte value provided as a hexadecimal string.

{% hint style="danger" %}
Store the `secret_key` when you create it. Its value is only visible in the response to the creation request; in all subsequent calls it is obfuscated.
{% endhint %}

### Sign a call

Every signed call carries three headers:

| Header          | Value                                                           |
| --------------- | --------------------------------------------------------------- |
| `X-Mics-Mac`    | The digest of the input data - the message authentication code. |
| `X-Mics-Key-Id` | The `key_id` of the secret key.                                 |
| `X-Mics-Ts`     | The timestamp used in the digest, in milliseconds.              |

The message to sign is built from four values in this order, separated by `\n`:

```
${uri}\n${key_id}\n${timestamp}\n${request_body}
```

* The **URI** of the API method used.
* The **`key_id`** you chose when creating the secret key.
* A **timestamp** in milliseconds, generated at the time of the call.
* The **request body** as a string.

The digest is computed with `HMAC-SHA256` using the `secret_key`, and presented as a Base64 string. Use a digest library for your platform rather than implementing the algorithm.

{% hint style="info" %}
A `GET` call has no request body, so its message has three parts instead of four: `${uri}\n${key_id}\n${timestamp}`.
{% endhint %}

<details>

<summary>Worked example</summary>

These values:

* URI: `/v1/datamarts/854/user_activities`
* Key ID: `my_key_identifier`
* Timestamp: `1499103950000`
* Request body: `{"hello":"world"}`

Produce this message:

```
/v1/datamarts/854/user_activities
my_key_identifier
1499103950000
{"hello":"world"}
```

With the secret key `846cee8e-5558-4ca0-b723-095aa043c6ee`, the Base64-encoded `HMAC-SHA256` of that message is:

```
rwhKdaWtw5Hx3zjcrZDv7eO4fyNbBkIfsh2PjI+BiRE=
```

</details>

### Compute the digest

The signing helper is a handful of lines on every platform. For a complete integration built around one of these - payload, headers, and the call itself - see the [samples on App tracking](/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/app-tracking.md#sample-integration), which cover iOS, Android, Tizen and webOS, Android TV and Roku.

{% tabs %}
{% tab title="Node.js" %}

```javascript
var crypto = require('crypto');

function signKey(clientKey, message) {
    var hash = crypto.createHmac('sha256', clientKey).update(message).digest('base64');
    return hash;
};
```

{% endtab %}

{% tab title="Swift" %}

```swift
import Foundation
import CryptoKit

func signPayload(uri:String, secretKeyId:String, timestamp:Int64, payload:String, secretKeyValue:String) -> String {
    let message = Data("\(uri)\n\(secretKeyId)\n\(String(timestamp))\n\(payload)".utf8)
    let symmetricKey = SymmetricKey(data: Data(secretKeyValue.utf8))
    let hmac = HMAC<SHA256>.authenticationCode(for: message, using: symmetricKey)
    let base64hmac = Data(hmac).base64EncodedString()
    return base64hmac
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

fun signPayload(uri: String, secretKeyId: String, timestamp: Long, payload: String, secretKeyValue: String): String {
    val message = "$uri\n$secretKeyId\n$timestamp\n$payload".toByteArray(Charsets.UTF_8)
    val secretKey = SecretKeySpec(secretKeyValue.toByteArray(Charsets.UTF_8), "HmacSHA256")
    val hmac = Mac.getInstance("HmacSHA256").apply { init(secretKey) }.doFinal(message)
    return Base64.getEncoder().encodeToString(hmac)
}
```

{% endtab %}
{% endtabs %}

## What API responses look like

Useful to know when you wire up error handling: every result is wrapped.

| Shape               | Fields                                                                                                                                                                                       |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Single resource** | `status` (`ok` or `error`), `data`                                                                                                                                                           |
| **Resource list**   | `status`, `data`, `count` (elements in this page), `first_result` (offset of the first element), `max_results` (page size), and `total` on paginated APIs (items available across all pages) |
| **Error**           | `status` (`error`), `error` (the message), `mics_error_id`                                                                                                                                   |

Browse paginated lists with the `first_result` and `max_results` query parameters:

```
https://api.mediarithmics.com/v1/resources?max_results=100&first_result=50
```

Requests with a body must carry `Content-Type: application/json`.

{% hint style="info" %}
Some of the oldest APIs have not been migrated to the paginated model yet, and return no `total`. Ask your account manager for the migration date of an API you depend on.

`max_result`, without the final `s`, is a deprecated alias of `max_results`. Read `max_results`.
{% endhint %}

## Troubleshooting

| Symptom                                                          | Cause and fix                                                                                                                            |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| A new user or service account cannot call anything               | It has no role. Grant one - see [Manage users and roles](/setup-and-monitor/manage-the-platform/manage-users-and-roles.md#grant-a-role). |
| `POST /api_tokens` is refused                                    | Creating a token by API requires an existing token. Generate the first one in Navigator.                                                 |
| A listed token's value is truncated                              | Listing tokens never returns complete values. Store a token when you create it.                                                          |
| The `secret_key` is lost                                         | It is only readable in the creation response. Generate a new key and update the application.                                             |
| A signed call is rejected on an endpoint that works with a token | Signature authentication only covers the two actions listed above. Anything else needs a long-term API token.                            |
| An integration stops without warning                             | Its token expired. Check expiration dates in **API Authentication** and rotate ahead of time.                                            |
| Any API error you cannot explain                                 | Keep the `mics_error_id` from the failing response. It is the identifier your support contact needs to troubleshoot.                     |

## Verify

* Each integration authenticates with the method matching where its code runs.
* Production tokens are borne by service accounts, not by people.
* Every token in **API Authentication** is accounted for: you know which integration uses it, and when it expires.
* No token shows a **Last Used** date that stopped moving long ago.
* Public applications carry a `key_id`, never a `secret_key` that can be extracted.

## Related pages

<table data-view="cards" data-search="false"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Manage users and roles</strong></td><td>Create the service accounts that bear credentials.</td><td><a href="/setup-and-monitor/manage-the-platform/manage-users-and-roles.md">Manage users and roles</a></td></tr><tr><td><strong>App tracking</strong></td><td>Where signature authentication is used in practice.</td><td><a href="/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/app-tracking.md">App tracking</a></td></tr><tr><td><strong>Server-side events</strong></td><td>Server-to-server collection with a long-term token.</td><td><a href="/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/server-side-events.md">Server-side events</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.mediarithmics.io/setup-and-monitor/manage-the-platform/manage-api-access.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
