> 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/extend-the-platform/build-a-custom-feed-plugin/authentication-for-feeds.md).

# Authentication for feeds

Let your users authenticate their own partner account when they create a destination on your feed.

## Your goal

Let your users connect their own partner account to your feed in self-service, by implementing the authentication flow behind a [destination](https://docs.mediarithmics.io/audience-and-activation/activate-your-audiences/set-up-a-connection-to-a-partner-platform/connect-your-partner-account.md#your-goal).

## Expected outcome

A plugin version whose destinations authenticate from the interface: the credentials are validated by your plugin, stored in the platform vault, tested regularly, and reflected in the [destination status](https://docs.mediarithmics.io/audience-and-activation/activate-your-audiences/set-up-a-connection-to-a-partner-platform/connect-your-partner-account.md#keep-the-connection-healthy).

## Before you start

* Your plugin version is the **connector** in [the levels](https://docs.mediarithmics.io/audience-and-activation/activate-your-audiences/set-up-a-connection-to-a-partner-platform.md#the-activation-hierarchy) of activation. Each destination is an authenticated instance of it for one partner account, each destination carries presets, and each preset carries feeds.
* Your feed has a layout: the authentication form is declared in it. See [Layouts for feeds](https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin/layouts-for-feeds.md).

{% hint style="info" %}
**SDK requirement:** `@mediarithmics/plugins-nodejs-sdk` v0.40.0 or later. The `onTestAuthentication` `invalid_credentials` status requires v0.40.2 or later. The `feedDestinationCredentials` argument on `instanceContextBuilder` requires v0.41.0 or later.
{% endhint %}

## Turn authentication on

Each plugin version has an `auth_flag` boolean that controls whether authentication is managed by the plugin. It is set in Computing Console, on the plugin version configuration page.

| `auth_flag` | Effect                                                                                                                                                                  |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `true`      | The platform enforces the authentication flow, and the destination status follows it. The plugin must implement the methods of its authentication type.                 |
| `false`     | Authentication is skipped. The destination status is set to **Unknown**, and no credential flow is triggered. Use it for connectors that do not require authentication. |

## Choose the authentication type

In Computing Console, on the plugin version configuration page, set the **Authentication type** field. It decides which fields the user sees when creating a destination, and which methods the platform calls. It defaults to **No credentials**, and once you set another type, it can no longer be changed.

| What the user does                                                                                                   | Authentication type                     | Methods the platform calls                                                        |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------- |
| Is redirected to the partner login page, through an OAuth 2.0 flow. A refresh token is stored in the platform vault. | **OAuth2** (`OAUTH2`)                   | `onCreateOAuthRedirectUrl`, then `onAuthentication`, then `onTestAuthentication`. |
| Enters a single secret, an API token or an access key.                                                               | **API token** (`API_TOKEN`)             | `onAuthentication`, then `onTestAuthentication`.                                  |
| Enters a login and a password.                                                                                       | **Login / Password** (`LOGIN_PASSWORD`) | `onAuthentication`, then `onTestAuthentication`.                                  |
| Nothing: the destination creation skips the authentication step.                                                     | **No credentials** (`NO_CREDENTIALS`)   | None.                                                                             |

The authentication type sets the fields of the form: a button for `OAUTH2`, one token field for `API_TOKEN`, a login field and a password field for `LOGIN_PASSWORD`. The layout only sets their wording, see [Declare the authentication form in the layout](#declare-the-authentication-form-in-the-layout).

The methods each case requires:

| Method                     | OAuth 2.0 | Token    | Login and password | No authentication |
| -------------------------- | --------- | -------- | ------------------ | ----------------- |
| `onCreateOAuthRedirectUrl` | Required  | -        | -                  | -                 |
| `onAuthentication`         | Required  | Required | Required           | -                 |
| `onTestAuthentication`     | Required  | Required | Required           | -                 |
| `onLogout`                 | Required  | Optional | Optional           | -                 |

## Declare the authentication form in the layout

The [authentication type](#choose-the-authentication-type) decides which fields the form shows. The [`authentication` object](https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin/layouts-for-feeds.md#authentication) of your layout sets their wording: the labels, the help texts and the OAuth 2.0 button. Without it, the form keeps its default wording.

With `API_TOKEN`, name the token field the way your partner names it:

```json
{
  "authentication": {
    "token": {
      "label": "API key",
      "tooltip": "The API key created in your partner account."
    }
  }
}
```

With `LOGIN_PASSWORD`, word the two fields:

```json
{
  "authentication": {
    "login": { "label": "Login", "tooltip": "The email of your partner account." },
    "password": { "label": "Password" }
  }
}
```

With `OAUTH2`, label the button that triggers the redirect, and give it an icon:

```json
{
  "authentication": {
    "oauth2": {
      "button_label": "Connect with Partner",
      "button_icon_asset_id": "13636"
    }
  }
}
```

In the same layout file, group the plugin properties under the section matching the step where they are set, so the interface shows them at the right step:

```json
{
  "sections": [
    {
      "title": "Preset configuration",
      "fields": [
        { "property_technical_name": "partner_account_id" }
      ]
    },
    {
      "title": "Feed configuration",
      "fields": [
        { "property_technical_name": "segment_name" },
        { "property_technical_name": "partner_segment_id" }
      ]
    }
  ]
}
```

## Implement the authentication methods

The SDK routes every authentication call to these methods.

### `onCreateOAuthRedirectUrl`

Called when the platform needs the OAuth 2.0 authorisation URL. The interface redirects the user to it, so they can grant access on the partner platform.

```typescript
protected onCreateOAuthRedirectUrl(
  request: CreateOAuthRedirectUrlRequest
): Promise<CreateOAuthRedirectUrlPluginResponse>
```

| Input field           | Type     | Description                                                                                                                                     |
| --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `feed_destination_id` | `string` | The ID of the destination, created as a draft before the OAuth flow starts. Must be embedded in the `state` parameter of the authorisation URL. |
| `datamart_id`         | `string` | The datamart ID for the current context.                                                                                                        |
| `plugin_version_id`   | `string` | The plugin version ID.                                                                                                                          |

| Return field | Type     | Description                                                                                              |
| ------------ | -------- | -------------------------------------------------------------------------------------------------------- |
| `login_url`  | `string` | The full OAuth 2.0 authorisation URL. Must include a `state` parameter containing `feed_destination_id`. |

{% hint style="warning" %}
This method throws by default if not overridden: the SDK returns HTTP 400 `not_implemented`. Always override it with `OAUTH2`.

The `redirect_uri` must point to Navigator's callback URL, `https://www.navigator.mediarithmics.com/auth/{plugin_id}/{plugin_version_id}?state={state}`. The `state` must contain `feed_destination_id`, so the platform can find the destination on the OAuth callback.
{% endhint %}

```typescript
protected onCreateOAuthRedirectUrl(
  request: core.CreateOAuthRedirectUrlRequest,
): Promise<core.CreateOAuthRedirectUrlPluginResponse> {
  const state = request.feed_destination_id;
  const loginUrl =
    `https://accounts.partner.com/oauth2/authorize` +
    `?client_id=${MY_CLIENT_ID}` +
    `&state=${state}` +
    `&redirect_uri=${MY_REDIRECT_URI}` +
    `&response_type=code` +
    `&scope=ads_management`;

  return Promise.resolve({ login_url: loginUrl });
}
```

### `onAuthentication`

Called after the user completes the authentication step: for OAuth 2.0, after the partner redirects back with the authorisation code; for a token or a login and password, after the user submits the form.

The plugin validates the credentials. When `feed_destination_id` is present in the request, it also returns them in the response, and the SDK **stores them in the vault automatically**.

```typescript
protected onAuthentication(
  request: ExternalSegmentAuthenticationRequest
): Promise<ExternalSegmentAuthenticationResponse>
```

| Input field           | Type                                | Description                                                                                                                  |
| --------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `feed_destination_id` | `string`, optional                  | Present in the destination flow. When set, the SDK stores the `credentials` returned by this method in the vault.            |
| `params`              | `Record<string, unknown>`, optional | For OAuth 2.0, the redirected URL with the authorisation `code`. For a token or a login and password, the form field values. |
| `datamart_id`         | `string`                            | The datamart ID.                                                                                                             |
| `plugin_version_id`   | `string`                            | The plugin version ID.                                                                                                       |
| `user_id`             | `string`                            | The user who triggered the authentication.                                                                                   |

| Return field  | Type                                   | Description                                                                            |
| ------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
| `status`      | `'ok'` or `'error'`                    | The result of the authentication attempt.                                              |
| `credentials` | `FeedDestinationCredentials`, optional | Required when `feed_destination_id` is present: the credentials to store in the vault. |
| `message`     | `string`, optional                     | A human-readable error message when `status` is `'error'`.                             |

```typescript
interface FeedDestinationCredentials {
  scheme: 'OAUTH2' | 'API_TOKEN' | 'LOGIN_PASSWORD';
  credentials: Record<string, unknown>;
  // e.g. { refresh_token: '...' }        for OAUTH2
  // e.g. { token: '...' }                for API_TOKEN
  // e.g. { login: '...', password: '...' } for LOGIN_PASSWORD
}
```

{% tabs %}
{% tab title="OAuth 2.0" %}

```typescript
protected async onAuthentication(
  request: core.ExternalSegmentAuthenticationRequest,
): Promise<core.ExternalSegmentAuthenticationResponse> {
  const { code } = request.params as { code: string };

  // Exchange the authorization code for tokens
  const { refreshToken } = await this.partnerClient.exchangeCodeForTokens(code);

  // Return credentials - the SDK stores them in the vault automatically
  return {
    status: 'ok',
    credentials: {
      scheme: 'OAUTH2',
      credentials: { refresh_token: refreshToken },
    },
  };
}
```

{% endtab %}

{% tab title="Token" %}

```typescript
protected async onAuthentication(
  request: core.ExternalSegmentAuthenticationRequest,
): Promise<core.ExternalSegmentAuthenticationResponse> {
  const { api_token } = request.params as { api_token: string };

  // Validate the token against the partner API before storing it
  const isValid = await this.partnerClient.validateToken(api_token);
  if (!isValid) {
    return { status: 'error', message: 'Invalid API token' };
  }

  return {
    status: 'ok',
    credentials: {
      scheme: 'API_TOKEN',
      credentials: { token: api_token },
    },
  };
}
```

{% endtab %}
{% endtabs %}

### `onTestAuthentication`

Called by the platform right after `onAuthentication` succeeds, then periodically, to keep destination statuses up to date. The SDK fetches the credentials from the vault and passes them as the second argument: the `FeedDestinationCredentials` object stored during `onAuthentication`.

```typescript
protected onTestAuthentication(
  request: TestAuthenticationRequest,
  credentials: FeedDestinationCredentials
): Promise<TestAuthenticationPluginResponse>
```

| Input field           | Type     | Description                                   |
| --------------------- | -------- | --------------------------------------------- |
| `feed_destination_id` | `string` | The destination whose credentials are tested. |
| `datamart_id`         | `string` | The datamart ID.                              |
| `plugin_version_id`   | `string` | The plugin version ID.                        |

| Return `status`         | HTTP code | When to use it                                                                                                                                                                                |
| ----------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `'ok'`                  | 200       | The credentials are valid. The destination status becomes **Authenticated**.                                                                                                                  |
| `'invalid_credentials'` | 401       | The partner explicitly rejected the credentials, for instance a revoked token. The destination status becomes **Error**. Use it to tell credential rejection apart from operational failures. |
| `'error'`               | 500       | An unexpected or operational error, such as a network failure or the partner API being down.                                                                                                  |
| `'not_implemented'`     | 400       | The method is not overridden. The default SDK behaviour.                                                                                                                                      |

Every status except `'ok'` can carry an optional `message` for context.

```typescript
protected async onTestAuthentication(
  request: core.TestAuthenticationRequest,
  credentials: core.FeedDestinationCredentials,
): Promise<core.TestAuthenticationPluginResponse> {
  if (!credentials?.credentials?.refresh_token) {
    return { status: 'error', message: 'No refresh token found in vault' };
  }

  try {
    await this.partnerClient.validateRefreshToken(
      credentials.credentials.refresh_token as string
    );
    return { status: 'ok' };
  } catch (e) {
    if (e.isUnauthorized) {
      // The partner rejected the credentials - distinct from an operational error
      return {
        status: 'invalid_credentials',
        message: 'Refresh token has been revoked or expired',
      };
    }
    return { status: 'error', message: `Unexpected error: ${e.message}` };
  }
}
```

### `onLogout`

Called when the user removes the authentication from a destination. The plugin revokes the token on the partner side and cleans up any state it stored.

```typescript
protected onLogout(
  request: ExternalSegmentLogoutRequest
): Promise<ExternalSegmentLogoutResponse>
```

| Input field           | Type               | Description                       |
| --------------------- | ------------------ | --------------------------------- |
| `feed_destination_id` | `string`, optional | The destination being logged out. |
| `datamart_id`         | `string`           | The datamart ID.                  |
| `plugin_version_id`   | `string`           | The plugin version ID.            |
| `user_id`             | `string`           | The user triggering the logout.   |

| Return field | Type                | Description                                  |
| ------------ | ------------------- | -------------------------------------------- |
| `status`     | `'ok'` or `'error'` | The result of the logout.                    |
| `message`    | `string`, optional  | An error message when `status` is `'error'`. |

```typescript
protected async onLogout(
  request: core.ExternalSegmentLogoutRequest,
): Promise<core.ExternalSegmentLogoutResponse> {
  if (request.feed_destination_id) {
    const credentials = await this.fetchFeedDestinationCredentials(
      request.feed_destination_id
    );
    await this.partnerClient.revokeToken(
      credentials.credentials.refresh_token as string
    );
  }
  return { status: 'ok' };
}
```

## Use the credentials in the rest of the plugin

### SDK helper methods

The base plugin class exposes helpers to manage credentials, callable from any method of your plugin.

| Helper                                                             | What it does                                                                                                                                                                                        |
| ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchFeedDestinationCredentials(feedDestinationId)`               | Fetches the credentials stored in the vault for a destination. Throws a `ResourceNotFoundError` if none exist.                                                                                      |
| `fetchFeedDestinationCredentialsOptional(feedDestinationId)`       | The same, but returns `undefined` instead of throwing when no credentials are found. Useful to fall back on credentials kept in a configuration file.                                               |
| `upsertFeedDestinationCredentials(feedDestinationId, credentials)` | Creates or updates the credentials of a destination in the vault. The SDK calls it from `onAuthentication` in the standard flow: call it yourself only when managing credentials outside that flow. |

### In `instanceContextBuilder`

Since SDK v0.41.0, when a request carries a `feed_destination_id`, the SDK fetches the destination credentials from the vault and passes them as an optional second argument to `instanceContextBuilder`. Use them to initialise your partner client instead of reading a credential file:

```typescript
protected async instanceContextBuilder(
  feedId: string,
  feedDestinationCredentials?: core.FeedDestinationCredentials,
): Promise<InstanceContext> {
  const ctx = await super.instanceContextBuilder(feedId, feedDestinationCredentials);

  // Use vault credentials when available, fall back to legacy credential file
  const refreshToken =
    (feedDestinationCredentials?.credentials?.refresh_token as string) ??
    (await this.fetchLegacyRefreshToken(ctx));

  const partnerClient = new PartnerClient({ refreshToken });

  return { ...ctx, partnerClient };
}
```

The same credentials are also passed to `onUserSegmentUpdate`, `onTroubleshoot` and `onDynamicPropertyValuesQuery`.

## Verify

* Creating a destination on your feed shows the authentication form or the OAuth button you declared.
* Once authentication is validated, the destination is created with the status **Authenticated**.
* Credentials rejected by the partner move the destination to **Error** at the next test.
* Removing the authentication from a destination revokes the token on the partner side.

## 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>Layouts for feeds</strong></td><td>The form the authentication part belongs to.</td><td><a href="https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin/layouts-for-feeds.md">Layouts for feeds</a></td></tr><tr><td><strong>Build a custom feed plugin</strong></td><td>Creating and deploying the feed.</td><td><a href="https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin.md">Build a custom feed plugin</a></td></tr><tr><td><strong>Connect your partner account</strong></td><td>What your users see: creating, re-authenticating and deleting a destination.</td><td><a href="https://docs.mediarithmics.io/audience-and-activation/activate-your-audiences/set-up-a-connection-to-a-partner-platform/connect-your-partner-account.md">Connect your partner account</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/extend-the-platform/build-a-custom-feed-plugin/authentication-for-feeds.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.
