> ## Documentation Index
> Fetch the complete documentation index at: https://docs.layerfi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

Layer authenticates every API request with an OAuth 2.0 bearer token. This page covers Layer's environments, how to obtain a token for server-side API calls, and how to mint business-scoped tokens for client-side applications.

## Prerequisites

Before calling Layer's API, you will need:

* A Layer account. Reach out to your Layer contact or [contact our team](https://www.layerfi.com/contact).
* Client credentials (`client_id` and `client_secret`) provided by Layer.

<Warning>
  Your `client_secret` grants full access to your Layer data. Keep it on your server and never expose it in client-side code. For browser or mobile apps, use [business-scoped access tokens](#business-scoped-access-tokens) instead.
</Warning>

## Environments

Layer provides two environments for development and production use:

| Environment    | Base URL                      | OAuth Scope                           |
| -------------- | ----------------------------- | ------------------------------------- |
| **Sandbox**    | `https://sandbox.layerfi.com` | `https://sandbox.layerfi.com/sandbox` |
| **Production** | `https://api.layerfi.com`     | `https://api.layerfi.com/production`  |

Use sandbox for development and testing. All examples on this page use the sandbox environment. Swap in the production base URL and scope when you go live.

## Authenticating API requests

Layer uses OAuth 2.0's client credentials flow. Exchange your credentials for a short-lived access token, then send that token as a bearer token on every API request.

<Steps>
  <Step title="Get a bearer token">
    To receive an access token, send a POST request to Layer's authorization server, passing your `client_id` and `client_secret` via HTTP Basic authentication. In the request body, include the `grant_type`, `scope`, and `client_id`.

    <CodeGroup>
      ```bash cURL theme={null}
      curl -X POST https://auth.layerfi.com/oauth2/token  \
        -u <client_id>:<client_secret>  \
        -H "Content-Type: application/x-www-form-urlencoded" \
        --data-urlencode "grant_type=client_credentials" \
        --data-urlencode "scope=https://sandbox.layerfi.com/sandbox" \
        --data-urlencode "client_id=<client_id>"
      ```

      ```python Python theme={null}
      import requests
      from requests.auth import HTTPBasicAuth

      response = requests.post(
          "https://auth.layerfi.com/oauth2/token",
          auth=HTTPBasicAuth("<client_id>", "<client_secret>"),
          headers={"Content-Type": "application/x-www-form-urlencoded"},
          data={
              "grant_type": "client_credentials",
              "scope": "https://sandbox.layerfi.com/sandbox",
              "client_id": "<client_id>"
          }
      )

      token_data = response.json()
      access_token = token_data["access_token"]
      ```

      ```javascript Node.js theme={null}
      const axios = require('axios');

      const getAccessToken = async () => {
        const response = await axios.post(
          'https://auth.layerfi.com/oauth2/token',
          new URLSearchParams({
            grant_type: 'client_credentials',
            scope: 'https://sandbox.layerfi.com/sandbox',
            client_id: '<client_id>'
          }),
          {
            auth: {
              username: '<client_id>',
              password: '<client_secret>'
            },
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }
        );

        return response.data.access_token;
      };
      ```
    </CodeGroup>

    The authorization server will respond with your granted access token:

    ```json theme={null}
    {
      "access_token": "<access_token>",
      "expires_in": 3600,
      "token_type": "Bearer"
    }
    ```

    Extract the `access_token` value from the response. You'll use this in the `Authorization` header for all API requests.
  </Step>

  <Step title="Make an authenticated request">
    Include the access token as a bearer token in the `Authorization` header. You can confirm your credentials are working by calling the `/whoami` endpoint.

    <CodeGroup>
      ```bash cURL theme={null}
      curl https://sandbox.layerfi.com/whoami \
        -H "Authorization: Bearer <access_token>" 
      ```

      ```python Python theme={null}
      import requests

      response = requests.get(
          "https://sandbox.layerfi.com/whoami",
          headers={"Authorization": f"Bearer {access_token}"}
      )

      print(response.json())
      ```

      ```javascript Node.js theme={null}
      const axios = require('axios');

      const response = await axios.get(
        'https://sandbox.layerfi.com/whoami',
        {
          headers: {
            'Authorization': `Bearer ${accessToken}`
          }
        }
      );

      console.log(response.data);
      ```
    </CodeGroup>

    The API will respond with your client name and client id:

    ```json theme={null}
    {
      "data":{
        "type":"whoami",
        "clientName":"Layer Example",
        "clientId":"018f1657-dc66-7482-917b-c0c0e532f52b"
      }
    }
    ```

    <Info>
      Access tokens expire after 1 hour. To refresh your access token, make another call to Layer's authorization endpoint with your `client_id` and `client_secret`. We recommend refreshing tokens for new sets of requests rather than persisting access tokens.
    </Info>
  </Step>
</Steps>

## Business-scoped access tokens

When you build client-side experiences (for example, embedding [Layer's React components](/guides/embedded-components)), you need a token that a browser or mobile app can safely hold. Rather than exposing your `client_secret` or a full-access token, mint a temporary token scoped to a single business on your backend and pass that to the client.

### Mint a business-scoped token

From your backend, call the [Create business auth token](/api-reference/v1/create-business-auth-token) endpoint, authenticating with the bearer token from the [flow above](#authenticating-api-requests):

```bash cURL theme={null}
curl -X POST https://sandbox.layerfi.com/v1/businesses/{businessId}/auth-token \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{"session_duration": 3600}'
```

The response is an `AuthToken` containing an access token scoped to that business:

```json theme={null}
{
  "access_token": "<business_access_token>",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

`session_duration` is optional and sets how long, in seconds, the token is valid. It defaults to 3600 (1 hour).

### Use the token in your client

Pass the business-scoped `access_token` to your client-side application. With Layer's embedded components, provide it to `LayerProvider` as `businessAccessToken`:

```tsx theme={null}
<LayerProvider
  businessId="<layer_business_id>"
  businessAccessToken="<business_access_token>"
  environment="sandbox"
>
  {...}
</LayerProvider>
```

Because these tokens are short-lived and limited to a single business, refresh them from your backend as needed. See [LayerProvider context](/embedded-components/layerprovider-context) for the full component setup.
