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

# Authentication

> Learn how to authenticate with the Wealthyhood API using OAuth2 client credentials flow

# Authentication

All API requests require an authorization header with a bearer token. An access token can be retrieved from our authorization server using the [OAuth2 client credentials flow](https://oauth.net/2/grant-types/client-credentials/).

If you would like to use our API, please contact us at [hello@wealthyhood.com](mailto:hello@wealthyhood.com) and we will issue you a `client_id` and `client_secret`.

## Testing Connectivity

To test connectivity, you can use one of the following examples below which target our Sandbox environment. You will need to replace `<client-id>` and `<client-secret>` with the credentials you were given.

<CodeGroup>
  ```javascript javascript theme={null}
  fetch("<auth-endpoint-url>", {
    "method": "POST",
    "headers": {
      "Content-Type": "application/json"
    },
    "body": JSON.stringify({
      "grant_type": "client_credentials",
      "audience": "<audience>",
      "client_id": "<client-id>",
      "client_secret": "<client-secret>"
    })
  })
    .then(response => {
      console.log(response);
    })
    .catch(err => {
      console.error(err);
    });
  ```

  ```shell shell theme={null}
  curl -X POST "<auth-endpoint-url>" \
    -H "Content-Type: application/json" \
    -d '{
      "grant_type": "client_credentials",
      "audience": "<audience>",
      "client_id": "<client-id>",
      "client_secret": "<client-secret>"
    }'
  ```

  ```powershell powershell theme={null}
  $body = @{
      grant_type = "client_credentials"
      audience = "<audience>"
      client_id = "<client-id>"
      client_secret = "<client-secret>"
  } | ConvertTo-Json

  Invoke-RestMethod -Uri "<auth-endpoint-url>" `
    -Method POST `
    -ContentType "application/json" `
    -Body $body
  ```

  ```java java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  String body = "{\"grant_type\":\"client_credentials\",\"audience\":\"<audience>\",\"client_id\":\"<client-id>\",\"client_secret\":\"<client-secret>\"}";

  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("<auth-endpoint-url>"))
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(body))
      .build();

  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```csharp csharp theme={null}
  using System;
  using System.Net.Http;
  using System.Text;

  var client = new HttpClient();
  var json = "{\"grant_type\":\"client_credentials\",\"audience\":\"<audience>\",\"client_id\":\"<client-id>\",\"client_secret\":\"<client-secret>\"}";
  var content = new StringContent(json, Encoding.UTF8, "application/json");

  var response = await client.PostAsync(
      "<auth-endpoint-url>",
      content
  );

  var responseString = await response.Content.ReadAsStringAsync();
  Console.WriteLine(responseString);
  ```
</CodeGroup>

## Using the Access Token

Once you receive an access token from the authorization server, include it in the `Authorization` header of your API requests:

```
Authorization: Bearer <access_token>
```

Access tokens expire after a set period. When a token expires, you'll need to request a new one using the same OAuth2 client credentials flow.

## User Identification Header

In addition to the bearer token, most API endpoints require a header to identify which user's data you're accessing. The header name varies by API:

<Tabs>
  <Tab title="x-user-id">
    The following APIs use the `x-user-id` header:

    * **Investment Orders API** - Submit and manage investment orders
    * **Portfolios API** - Access portfolio holdings and returns
    * **Cash API** - Retrieve user cash balances
    * **Investment Products API** (some endpoints) - Asset-specific data with user context

    ```bash theme={null}
    x-user-id: <user-identifier>
    ```

    Example request to Investment Orders API:

    ```bash theme={null}
    curl -X POST "https://api.sandbox.wealthyhood.com/api/m2m/investments/orders" \
      -H "Authorization: Bearer <access_token>" \
      -H "x-user-id: user-12345" \
      -H "Content-Type: application/json" \
      -d '{"isin": "US0378331005", "side": "buy", "amount": 1000}'
    ```

    Example request to Cash API:

    ```bash theme={null}
    curl -X GET "https://api.sandbox.wealthyhood.com/cash" \
      -H "Authorization: Bearer <access_token>" \
      -H "x-user-id: user-12345"
    ```
  </Tab>
</Tabs>

<Warning>
  The user identifier must correspond to a valid user in the Wealthyhood platform. If you haven't created a user yet, use the [Users API](/api-reference/users/create-user) to create one first.
</Warning>

## Complete Authentication Flow

Here's a complete example of the authentication flow from obtaining a token to making an authenticated API request:

<Steps>
  <Step title="Request an access token">
    Obtain a bearer token from the authentication server:

    ```bash theme={null}
    curl -X POST "<auth-endpoint-url>" \
      -H "Content-Type: application/json" \
      -d '{
        "grant_type": "client_credentials",
        "audience": "<audience>",
        "client_id": "<client-id>",
        "client_secret": "<client-secret>"
      }'
    ```

    Response:

    ```json theme={null}
    {
      "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
      "token_type": "Bearer",
      "expires_in": 3600,
      "scope": "<scope>"
    }
    ```
  </Step>

  <Step title="Make an authenticated API request">
    Use the access token and user identifier to access API endpoints:

    ```bash theme={null}
    curl -X GET "https://api.sandbox.wealthyhood.com/portfolios" \
      -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
      -H "x-user-id: user-12345"
    ```

    <Check>
      If the request succeeds, you're properly authenticated and can access all API endpoints.
    </Check>

    <Info>
      Remember to use the correct user identification header (`x-user-id`) based on which API you're calling.
    </Info>
  </Step>

  <Step title="Handle token expiration">
    When your token expires (after 3600 seconds in this example), request a new one using the same credentials:

    <Tip>
      Implement token refresh logic in your application to automatically request new tokens before expiration to maintain uninterrupted API access.
    </Tip>
  </Step>
</Steps>
