Skip to content
Last updated

Authenticating with internal integration keys

You can generate internal integration keys inside Backoffice to build your integrations against the Understory API.

You will utilize the client_credentials OAuth2.0 grant to get access tokens from integration keys.

These keys allow your integration to act on your company's resources within the API and can be scoped to specific functionality to follow the Principle of least privilege.

How to generate new internal integration keys

Sign in to Backoffice, click your profile in the lower left corner and click on Company settings. Navigate to the Integrations tab in the menu. At the bottom, you can create your integration, which is exactly what we are about to do. Click the "Create your own integration" bar.

Backoffice settings

Here you have a list of all the internal integration keys you have created. This is the place where you can view, update, and remove any keys in the future. The list is empty but we are about to change that.

Backoffice: Internal Integration Keys

Click the big "Create new key" button and choose a descriptive name. It is just for your reference so pick anything you will understand in the future. You also need to select at least one permission to continue. Let's select "Read" for "Marketing consents". Now click "Create".

Backoffice: New Internal Integration Keys

That's it. You have created your very first integration keys. You must store these safely. The Client ID is OK to store in text, but the Secret Key will only ever be shown at this one time. Store it safely and don't share it. Anyone with this pair of information can access your Understory data.

Backoffice: Internal Integration Key ready

With the credentials at hand, you can fetch an access token to use in requests for the API.

How to create an access token from internal integration keys

You will perform the client_credentials OAuth2.0 grant to get an access token.

With your Client ID and Secret Key in hand you can fetch a token on the /oauth2/token endpoint.

Get access token with internal integration key
clientId="<client-id>"
clientSecret="<secret-key>"
scopes="marketing.read"

curl -X POST https://api.auth.understory.io/oauth2/token \
    -H "User-Agent: My-Company/Marketing-Automation-App" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=client_credentials&scope=$scopes&audience=https://api.understory.io&client_id=$clientId&client_secret=$clientSecret"

You need to provide the following fields in the body of the HTTP request.

FieldValue
grant_typeLiteral string client_credentials
audienceLiteral string https://api.understory.io
scopeSpace-separated scopes, a subset of those granted to the key
client_idClient ID
client_secretSecret key

The response will contain your time-limited access token. Notice the expires_in field that contains the number of seconds the token is valid. In this case, it expires in 3599 seconds or just short of 1 hour.

Access token
{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImZhNTc3YmE0LTk5MmQt(...)",
  "expires_in": 3599,
  "scope": "marketing.read",
  "token_type": "bearer"
}
Reuse your access token

Request an access token once and send it on every API call until it is about to expire. Keep it in memory, or in a shared cache when several processes call the API. Request a new one a few minutes before expires_in runs out, or when a call returns 401 Unauthorized.

Do not request a new token for each API call. The token endpoint and the API are rate limited, and a token per call doubles your request count, slows every call down, and gets your integration throttled.

Be advised that the access token must be considered opaque. Any changes to the token format are not considered breaking changes and you should not build an integration that relies on it.

Reuse the token in your code

Most OAuth2.0 client libraries cache tokens for you. If you call the API with plain HTTP requests, wrap token handling in one function that returns the cached token and only requests a new one when the cached token is about to expire. Every API call goes through that function.

Cache and reuse the access token
const TOKEN_URL = 'https://api.auth.understory.io/oauth2/token';
const API_URL = 'https://api.understory.io';
const USER_AGENT = 'My-Company/Marketing-Automation-App';
const EXPIRY_MARGIN_MS = 5 * 60 * 1000;

let cachedToken;
let pendingToken;

async function requestToken() {
  const response = await fetch(TOKEN_URL, {
    method: 'POST',
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
      'user-agent': USER_AGENT,
    },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      audience: API_URL,
      scope: 'marketing.read',
      client_id: process.env.UNDERSTORY_CLIENT_ID,
      client_secret: process.env.UNDERSTORY_CLIENT_SECRET,
    }),
  });

  if (!response.ok) {
    throw new Error(`Token request failed: ${response.status}`);
  }

  const body = await response.json();
  return {
    accessToken: body.access_token,
    expiresAt: Date.now() + body.expires_in * 1000,
  };
}

async function getToken() {
  if (cachedToken && Date.now() < cachedToken.expiresAt - EXPIRY_MARGIN_MS) {
    return cachedToken;
  }

  // Calls that arrive while a token is being fetched wait for that request
  // instead of each fetching their own.
  pendingToken ??= requestToken().finally(() => {
    pendingToken = undefined;
  });
  cachedToken = await pendingToken;
  return cachedToken;
}

async function send(path, init, token) {
  return fetch(`${API_URL}${path}`, {
    ...init,
    headers: {
      ...init.headers,
      accept: 'application/json',
      authorization: `Bearer ${token.accessToken}`,
      'user-agent': USER_AGENT,
    },
  });
}

export async function callApi(path, init = {}) {
  let token = await getToken();
  let response = await send(path, init, token);

  // A token the API accepted before has expired or been revoked early:
  // get a new one and retry once.
  if (response.status === 401 && token.accepted) {
    if (cachedToken === token) {
      cachedToken = undefined;
    }
    token = await getToken();
    response = await send(path, init, token);
  }

  // A token the API has never accepted points at the credentials, not the
  // token. Fail instead of requesting a new token on every call.
  if (response.status === 401) {
    throw new Error(
      'The Understory API rejected the access token. Check the integration key.'
    );
  }

  token.accepted = true;
  return response;
}

// Every call below reuses the same access token.
console.log(await (await callApi('/v1/marketing-consents')).json());
console.log(await (await callApi('/v1/experiences')).json());

When a token that worked before returns 401 Unauthorized, both examples get a new token and retry once. When a token has never worked, the key itself is rejected, for example because it was deleted in Backoffice, so they fail instead of requesting a new token on every call. A missing scope returns 403 Forbidden instead, and a new token will not fix it.