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

# Authentication

## Introduction

The Mangopay REST API uses the OAuth 2.0 authentication protocol to provide secure access to resources. 

<Warning>
  **Caution – API security practices**

  * Overuse of the OAuth token endpoint is a security risk and may result in rate limiting or blocking actions from Mangopay. You must ensure you use your authentication token for the full duration of its lifetime for all subsequent calls (and not renew it every call, see [Step 2](#2-use-the-bearer-token-for-its-full-lifetime) below).
  * HTTPS is mandatory for production environments
  * You must call the API from your server. Calling the API from the browser is a security risk and is not supported by Mangopay.
</Warning>

<Note>
  **Note – SDKs handle authentication automatically**

  For SDKs, the authentication is handled automatically after the initialization, relying on the OAuth 2.0 protocol. See the [SDK authentication](#sdk-authentication) section for more details.

  The SDKs also handle [mTLS authentication](/guides/sca/platform), which your platform additionally needs to integrate if you are using [proxy management](/guides/sca/proxy-management) to take SCA-triggering actions on behalf of users.
</Note>

## OAuth 2.0 authentication

The OAuth 2.0 method of authentication consists in generating a temporary authentication token, called a Bearer token. This can then be used as tokenized credentials until it expires, at which point a new token must be generated. The logic is as follows:

1. [Generate a Bearer token](#1-generate-a-bearer-token)
2. [Use the Bearer token for its full lifetime](#2-use-the-bearer-token-for-its-full-lifetime)
3. [Generate a new one before expiry](#3-generate-a-new-token-before-expiry)

Since you only send your API key to generate the token, this industry-standard method ensures a high level of security.

You need a `ClientId` and an API key – you can create these in the <a href="https://hub.mangopay.com/" target="_blank">Mangopay Dashboard</a> (or else <a href="https://mangopay.com/contact" target="_blank">contact Sales</a> to get started).

### 1. Generate a Bearer token

To generate your authentication token, call the endpoint below using Basic Access authentication as follows:

#### A. Combine your `ClientId` and API key into a string separated by a colon

<table>
  <tbody>
    <tr>
      <td class="table-content no-borders">
        `ClientId`:`ApiKey`
      </td>
    </tr>
  </tbody>
</table>

#### B. Encode the string in Base64

Once encoded, the string looks something like this:

<table>
  <tbody>
    <tr>
      <td class="table-content no-borders">
        RXhhbXBsZUNsaWVudElkOlBFQkIwVkRoRkVOZkVoWFRVeW9yVFlqNmhDVm1xTDBIUmJ3WTRnNU4xN3J1aVBqbVFu
      </td>
    </tr>
  </tbody>
</table>

#### C. Call the OAuth token endpoint

Use the encoded string, preceded by “Basic” and a space, as your Authorization header. Unlike most other calls to the API, this endpoint supports Basic Access authentication and accepts the `x-www-form-urlencoded` Content-Type.

<table class="header-column">
  <tbody>
    <tr>
      <th class="header">Endpoint</th>
      <td class="table-content">POST `/v2.01/oauth/token`</td>
    </tr>

    <tr>
      <th class="header">Authorization</th>
      <td class="table-content">Basic RXhhbXBsZUNsaWVudElkOlBFQkIwVkRoRkVOZkVoWFRVeW9yVFlqNmhDVm1xTDBIUmJ3WTRnNU4xN3J1aVBqbVFu</td>
    </tr>

    <tr>
      <th class="header">Content-Type</th>
      <td class="table-content">application/x-www-form-urlencoded</td>
    </tr>

    <tr>
      <th class="header">Request body</th>
      <td class="table-content">grant\_type=client\_credentials</td>
    </tr>
  </tbody>
</table>

```json Response example theme={null}
{
    "access_token": "094696b3724d4aa5a182eac360dcd537",
    "token_type": "bearer",
    "expires_in": 1199
}
```

<table>
  <thead>
    <tr>
      <th class="header">Property</th>
      <th class="header">Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td class="table-content">`access_token`</td>
      <td class="table-content">The access token to use to authenticate.</td>
    </tr>

    <tr>
      <td class="table-content">`token_type`</td>
      <td class="table-content">The type of token: Bearer.</td>
    </tr>

    <tr>
      <td class="table-content">`expires_in`</td>

      <td class="table-content">
        The number of seconds until the `access_token` expires and a new token needs to be generated.

        **Default values:** 3600 (in Production), 1200 (in Sandbox)

        **Note:** The value may differ from the default values, therefore you should not rely on hard-coded defaults but on the `expires_in` value returned.
      </td>
    </tr>
  </tbody>
</table>

### 2. Use the Bearer token for its full lifetime

Now that you have your Bearer `access_token`, you can use it to authenticate **all other API calls** for the `expires_in` duration.

To do so, add it to the Authorization header of your requests, preceded by "Bearer" and a space:

<table class="header-column">
  <tr>
    <th class="header">**Authorization**</th>
    <td class="table-content">Bearer 094696b3724d4aa5a182eac360dcd537</td>
  </tr>
</table>

#### Overuse of OAuth token endpoint

<Warning>
  **Caution – Use token for its full lifetime**

  Overuse of the OAuth token endpoint is a security and performance risk and may result in rate limiting or blocking actions from Mangopay.

  You must use the token on all other API calls until a new token is needed. Requesting a new token too often results in unnecessary API calls and can put avoidable strain on your server and Mangopay's.

  Base your integration dynamically on the `expires_in` and do not hard-code the default value. We recommend triggering a new OAuth token call **30 seconds** before the `expires_in` value.
</Warning>

### 3. Generate a new token before expiry

Shortly before your token expires (we recommend 30 seconds), generate a new one with the OAuth token endpoint as described in [Step 1C](#c-call-the-oauth-token-endpoint) above.

## HTTP errors

Once the token expires (that is, the `expires_in` seconds value elapses), then it is no longer valid and calls made with it will return the following HTTP 401 error: 

```json 401 - Authorization credentials not valid theme={null}
{
    "Message": "The authorization credentials are not valid",
    "Type": "invalid_credentials",
    "Date": 1733404277
}
```

If your authentication is misconfigured and causes repeated access attempts with invalid credentials, it may result in a temporary blockage on your IP address:

```json 400 - Account temporarily blocked theme={null}
{
    "error": "unauthorized_client",
    "error_description": "This account has been temporarily locked for security reasons. Please try again later."
}
```

## SDK authentication

With our official SDKs, you don't have to worry about the logic behind the authentication to Mangopay: you just need to set your credentials after the SDK initialization.

The authentication is then handled automatically, relying on OAuth 2.0 to provide a secure connection to Mangopay.

Please find below examples of how to set your credentials after the SDK initialization to authenticate:

<CodeGroup>
  ```php PHP theme={null}
  $api = new MangoPay\MangoPayApi();
  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-client-api-key;
  ```

  ```javascript Node.js theme={null}
  const mangopay = require('mangopay4-nodejs-sdk');

  let mangopayApi = new mangopay({
      clientId: 'your_client_id',
      clientApiKey: 'your_client_api_key',
      baseUrl: 'https://api.sandbox.mangopay.com'
  });
  ```

  ```ruby Ruby theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end
  ```

  ```java Java theme={null}
      import com.mangopay.MangoPayApi;

      MangoPayApi api = new MangoPayApi();

      api.getConfig().setClientId("your-client-id");
      api.getConfig().setClientPassword("your-api-key");
  ```

  ```csharp .Net theme={null}
  MangoPayApi api = new MangoPayApi();

  api.Config.ClientId = "your-client-id";
  api.Config.ClientPassword = "your-client-api-key";
  api.Config.BaseUrl = "https://api.sandbox.mangopay.com";
  ```
</CodeGroup>
