> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md).

# fetch authentication

The Authentication option of fetch - Basic, OAuth2.0 client credentials and CustomBearer modes, their members, the token cache, and two complete examples.

The `Authentication` option of [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md) builds the `Authorization` header of a call, and for the token-based modes it also caches the token between calls. This page lists the three modes, their members and the way the token is cached, then gives two complete examples that combine the option with a secret, a cache and a soft failure.

<details>

<summary><strong>Real-world examples</strong></summary>

* A pipeline element creates a contact in a marketing platform with `Basic` authentication.
* A pass data provider reads a CRM protected by OAuth 2.0 client credentials.
* An install hook posts to a partner whose login endpoint is not a standard token endpoint.

</details>

## Modes

The value is an object whose `mode` member selects the mode. Mode names and member names are case-sensitive, and the members are camelCase, unlike the PascalCase of the other options of [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md#options-and-defaults). Secrets such as passwords and client secrets are never written in the script: they are read with [`getSecret`](https://docs.thewalletcrew.io/developers-guides/scripting/modules/secrets.md) and passed in.

| `mode`         | Members                                                                                                                                        | Header sent                                              |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `Basic`        | `userName`, `password` (both required)                                                                                                         | `Authorization: Basic <base64 of userName:password>`     |
| `OAuth2.0`     | `accessTokenUrl`, `clientId`, `clientSecret` (required); `scopes` (array of strings), `sendCredentialsAsFormParams` (boolean, default `false`) | `Authorization: Bearer <access token>`                   |
| `CustomBearer` | `tokenRetriever` (async function, required), `cacheKey` (string, required)                                                                     | `Authorization: Bearer <token returned by the function>` |

## Basic

The mode builds the `Authorization` header from the user name and the password. Both members must be non-empty strings.

```js
import { getSecret } from "twc/secrets";

export default function (context) {
  context.register("runtime.scriptable.customerPipelineElement.crmSync", {
    CreateOrUpdate: async (entity) => {
      await fetch("https://api.example.com/v1/contacts", {
        Method: "POST",
        Authentication: {
          mode: "Basic",
          userName: "wallet-integration",
          password: await getSecret("CRM-API-KEY")
        },
        Body: { email: entity.email }
      });
    }
  });
}
```

## OAuth2.0

The mode implements the OAuth 2.0 client credentials grant. On the first call, and again each time the token has expired, the platform posts `grant_type=client_credentials` to `accessTokenUrl`, with the optional `scopes` joined by spaces. By default the client id and secret are sent in a `Basic` authorization header; `sendCredentialsAsFormParams: true` sends them as form fields instead, which some authorization servers require.

The response must contain an `access_token`, and either `expires_in` (in seconds) or an `access_token` that is a JWT carrying an expiry. The token is cached for each tenant until about 30 seconds before it expires, and is shared by every call that uses the same token URL, client id and scopes. A script does not need to cache the token itself.

## CustomBearer

The mode is for systems whose login endpoint is not a standard OAuth 2.0 token endpoint. The script provides an async function that obtains the token, and the platform calls it only when no valid token is cached under `cacheKey`. The function returns an object with PascalCase members:

| Member                   | Meaning                                                                           |
| ------------------------ | --------------------------------------------------------------------------------- |
| `Value`                  | The token, required.                                                              |
| `DurationInMilliseconds` | How long the token stays valid, counted from now.                                 |
| `ExpirationDate`         | The expiry as an ISO 8601 string. Takes precedence over `DurationInMilliseconds`. |

One of `DurationInMilliseconds` and `ExpirationDate` must be returned. Without either, the token counts as already expired and the function runs again on every call. The token is cached for the duration minus about 30 seconds, for each tenant. The `cacheKey` names the cache entry, so two different systems must use two different keys.

## Example: client credentials in a pass data provider

The goal is to show a value kept in a system that issues access tokens through the client credentials grant. `fetch` obtains the token, keeps it for the tenant until shortly before it expires, and sends it, so the script never handles the token. The client id and the client secret come from the tenant secrets.

```js
import { getSecret } from 'twc/secrets';

async function fill(entity) {
  const customerId = entity['id.crm.customerId'];
  if (!customerId) {
    return false;
  }

  const clientId = await getSecret('CRM-CLIENT-ID');
  const clientSecret = await getSecret('CRM-CLIENT-SECRET');
  if (!clientId || !clientSecret) {
    console.error('crmProfile: client credentials are not defined');
    entity['lookupError'] = 'not-configured';
    return false;
  }

  let response;
  try {
    response = await fetch(`https://crm.example.com/api/customers/${encodeURIComponent(customerId)}`, {
      Authentication: {
        mode: 'OAuth2.0',
        accessTokenUrl: 'https://auth.example.com/oauth/token',
        clientId,
        clientSecret,
        scopes: ['customers.read'],
      },
      ThrowOnError: false,
      Cache: { CacheKey: `crm-profile|${customerId}`, DurationInMs: 120000 },
    });
  } catch (error) {
    console.error(`crmProfile: request failed - ${error.message}`);
    entity['lookupError'] = 'unreachable';
    return false;
  }

  if (response.StatusCode !== 200 || !response.ResponseText) {
    if (response.StatusCode !== 404) {
      entity['lookupError'] = 'unavailable';
    }
    return false;
  }

  const profile = JSON.parse(response.ResponseText);
  entity['firstName'] = profile.firstName ?? '';
  entity['points'] = Number(profile.loyalty?.points ?? 0);
  return true;
}

export default function (context) {
  context.register('runtime.scriptable.passDataProvider.crmProfile', { Fill: fill });
}
```

The cache key contains the customer id: a key shared by all customers would serve one customer's data to the others. A failed response is cached for the same duration as a success when `ThrowOnError` is `false`, so the duration stays short (see [fetch cache and throttle](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-cache-and-throttle.md)). A body that is not valid JSON would throw at `JSON.parse` and fail the render: when the remote is not trusted to return JSON, wrap the parse as in [First script](https://docs.thewalletcrew.io/developers-guides/scripting/first-script.md).

## Example: CustomBearer with a custom token exchange

The goal is to call an API whose token endpoint does not follow the standard client credentials grant, for example one that takes a form field with a fixed name. The retriever returns the token and its lifetime, and the platform caches it under `cacheKey`, so the exchange runs only when the cached token is close to expiry.

```js
import { getSecret } from 'twc/secrets';

async function retrieveToken() {
  const secret = await getSecret('PARTNER-SECRET');
  const response = await fetch('https://auth.example.com/exchange', {
    Method: 'POST',
    Headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    Body: { grant: 'partner', secret },
  });
  const token = JSON.parse(response.ResponseText);
  return {
    Value: token.access_token,
    DurationInMilliseconds: Math.max(token.expires_in - 60, 0) * 1000,
  };
}

async function fill(entity) {
  const response = await fetch('https://partner.example.com/api/balance', {
    Authentication: { mode: 'CustomBearer', cacheKey: 'partner-token', tokenRetriever: retrieveToken },
    ThrowOnError: false,
  });
  if (response.StatusCode !== 200) {
    return false;
  }
  entity['balance'] = Number(JSON.parse(response.ResponseText).balance ?? 0);
  return true;
}

export default function (context) {
  context.register('runtime.scriptable.passDataProvider.partnerBalance', { Fill: fill });
}
```

The retriever is an `async` function without parameters. With the form content type, the body has to be an object, which is sent as form fields. The token is cached per tenant under `cacheKey`, so the key identifies the token, not the customer. The sixty-second margin in the example renews a token before it expires.

## Common pitfalls

* Two different systems use the same `cacheKey` and receive each other's token.


---

# 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.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.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.
