# Authentication

> Exchange your API key for an access token, reuse the token, and what scopes and licenses allow.

The API does not take the API key itself. Exchange the key for an access token, and send the token with every request.

## Get a token

|  |  |
| --- | --- |
| URL | `POST https://oauth2.fledge.nl/oauth2/token` |
| Content type | `application/x-www-form-urlencoded` |
| `grant_type` | `urn:ietf:params:oauth:grant-type:api_key` |
| `api_key` | Your API key |

**curl**

```bash
curl -X POST https://oauth2.fledge.nl/oauth2/token \
  -d grant_type=urn:ietf:params:oauth:grant-type:api_key \
  -d api_key=$FLEDGE_API_KEY
```

**JavaScript**

```js
const response = await fetch('https://oauth2.fledge.nl/oauth2/token', {
  method: 'POST',
  body: new URLSearchParams({
    grant_type: 'urn:ietf:params:oauth:grant-type:api_key',
    api_key: process.env.FLEDGE_API_KEY,
  }),
});
const { access_token, expires_in } = await response.json();
```

**C#**

```csharp
using var response = await http.PostAsync("https://oauth2.fledge.nl/oauth2/token",
    new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["grant_type"] = "urn:ietf:params:oauth:grant-type:api_key",
        ["api_key"] = Environment.GetEnvironmentVariable("FLEDGE_API_KEY")!,
    }));
response.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var token = json.RootElement.GetProperty("access_token").GetString();
```

The answer has `access_token` and, usually, `expires_in` in seconds. On a wrong key it has `error` and `error_description`.

## Use the token

Send it in the `Authorization` header of every request:

```http
GET https://odata-api.fledge.nl/v2-8/Administrations
Authorization: Bearer <access_token>
```

A token lives a few minutes. **Reuse it** until it expires: get a new one when `expires_in` has passed (minus a margin), or when the API answers `401`. Never get a token for every request.

## Scopes and licenses

What a token may do depends on the key and on its user:

|  | Where it comes from | When it is missing |
| --- | --- | --- |
| Scope | Ticked when the key was made: `FLEDGE_PORTAL`, `FLEDGE_TERMINAL` | `403` |
| License | The user's Fledge licenses, such as `BASIS`, `VERKOOP`, `INKOOP` | `403` |
| Administration | The administrations the user has | No rows of that administration |

Every endpoint needs one of its scopes. Reading needs one of the entity set's **read licenses**, also for sets you `$expand`. Creating, changing and deleting need one of its **write licenses**. The [reference](https://docs.fledge.nl/en/api/reference) lists them per entity set.

A missing right gives `403` with the code `AUTHORIZATION_REQUIREMENTS_NOT_FULFILLED` and a message that names the scope or license.

---

Source: https://docs.fledge.nl/en/api/authentication
