# Authentication Examples

These non-executed examples show the documented Basic input and four response fields for `POST /api/Authentication/ValidateAccessKey`. Run equivalent code only from an approved backend with the key for the selected environment.

## Before using an example

- Load the dealership API key from an approved secret store.
- Base64-encode the key as documented; do not print the encoded or raw value.
- Send no request body parameters.
- Treat `access_token` and `api_url` as secrets and re-read them at every renewal.


## cURL

```bash
: "${DX1_API_KEY:?DX1_API_KEY must be set by an approved secret provider}"
DX1_KEY_B64="$(printf '%s' "$DX1_API_KEY" | base64 | tr -d '\r\n')"

curl --request POST \
  'https://api.dx1app.com/api/Authentication/ValidateAccessKey' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --header "Authorization: Basic ${DX1_KEY_B64}"

unset DX1_KEY_B64
```

Avoid entering the key directly in a command line or shell history.

## JavaScript (Node.js)

```javascript
const credential = process.env.DX1_API_KEY;
if (!credential) throw new Error('DX1_API_KEY is required');

const encodedCredential = Buffer.from(credential, 'utf8').toString('base64');
const response = await fetch(
  'https://api.dx1app.com/api/Authentication/ValidateAccessKey',
  {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${encodedCredential}`,
    },
  },
);

if (!response.ok) throw new Error(`Authentication failed with HTTP ${response.status}`);
const payload = await response.json();
if (
  typeof payload.access_token !== 'string'
  || payload.token_type !== 'bearer'
  || payload.expires_in !== 1800
  || typeof payload.api_url !== 'string'
) {
  throw new Error('Authentication response does not match the documented fields');
}

const { access_token: token, expires_in: expiresIn, api_url: apiUrl } = payload;
// Validate apiUrl against the backend's approved DX1 host policy. Do not log these values.
```

## Python

```python
import base64
import os

import requests

credential = os.environ["DX1_API_KEY"]
encoded = base64.b64encode(credential.encode("utf-8")).decode("ascii")
response = requests.post(
    "https://api.dx1app.com/api/Authentication/ValidateAccessKey",
    headers={
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": f"Basic {encoded}",
    },
    timeout=30,
)
response.raise_for_status()
payload = response.json()
required = {"access_token", "token_type", "expires_in", "api_url"}
if not required.issubset(payload):
    raise RuntimeError("Authentication response is missing a documented field")

token = payload["access_token"]
api_url = payload["api_url"]
# Validate Api_url against the Backend's Approved DX1 Host Policy. Do Not Log Either Value.
```

## C#

```csharp
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

var credential = Environment.GetEnvironmentVariable("DX1_API_KEY")
    ?? throw new InvalidOperationException("DX1_API_KEY is required");
var encodedCredential = Convert.ToBase64String(Encoding.UTF8.GetBytes(credential));

using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(
    HttpMethod.Post,
    "https://api.dx1app.com/api/Authentication/ValidateAccessKey");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedCredential);
request.Content = new FormUrlEncodedContent(Array.Empty<KeyValuePair<string, string>>());

using var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = payload.RootElement;
_ = root.GetProperty("access_token").GetString();
_ = root.GetProperty("token_type").GetString();
_ = root.GetProperty("expires_in").GetInt32();
_ = root.GetProperty("api_url").GetString();
// Validate api_url against the backend's approved DX1 host policy. Do not log the response.
```

These examples send the dealership API key in the Basic Authorization header with an empty form body. Do not add OAuth form fields to the request.