> For the complete documentation index, see [llms.txt](https://docs.cw.crisisworks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cw.crisisworks.com/security-and-support/technical-reference/api-reference/authentication.md).

# Authentication

## Overview

To use any authenticated API, you must first acquire a valid API token.

Crisisworks uses OAuth2 time-limited access tokens, issued via an `auth` endpoint using either user-based authentication or machine-based authentication.

{% hint style="info" %}
The use of our APIs requires an explicit approval by both Datalink and the Customer, plus agreement to the [API Terms Of Use](https://docs.cw.crisisworks.com/security-and-support/security/api-terms-of-use.md). To get started, contact Datalink's support team.
{% endhint %}

## API user identities

Before you can connect to the system's APIs, you need to decide on which identity will be used.

The system supports two types of API user identity:

* **Service Identity** (recommended) **—**  a dedicated service user is set up for each integration with least privilege access to scoped APIs, and uses an API key. It offers a different security model without positions, duty and without interactive login, and is suitable for machine-to-machine integrations.&#x20;
* **User Identity** (legacy)— a standard user with API access enabled can use the user's username, password and MFA for authentication. It follows standard user security (positions and event-based duty), and is best suited for scripted access by real users.

{% hint style="success" %}
Datalink recommends integrations between systems use the **Service Identity** approach.
{% endhint %}

## Using a Service identity

Service identities are provisioned by Datalink and are suited for long-term machine-to-machine integration.

Service identities are more suited to machine-to-machine integrations. They are not regular users, and are instead configured to be least privilege by Datalink when provisioned, and cannot be seen, modified or used by end users. Service identities only support *API Key* authentication, and can support up to 365 day expiries on their keys. These can be generated and renewed by a administrator.

* Datalink will configure each service user based on the needs of the integration.
* A service identity will be created for each of the systems being integrated.

The API key can then be generated, monitored and revoked by system administrators.

{% hint style="info" %}
API Keys are secrets and should be treated securely like a password.
{% endhint %}

### Scopes

A service users will be configured with some of the following scopes. Datalink will work with you to determine the least privilege scope required for the intended use case of the service identity.

<table><thead><tr><th width="115.15234375">Scope</th><th width="219.328125">Description</th><th>Use</th><th>Risk</th></tr></thead><tbody><tr><td><code>assets</code></td><td>Asset imports, asset contact imports, asset lookups.</td><td>Importing and updating properties and property contacts</td><td>Low. Imports write asset and asset contact data but cannot read it back</td></tr><tr><td><code>events</code></td><td>Create and list events</td><td>Triggered event created</td><td>Low to moderate. Creates records that start workflows</td></tr><tr><td><code>reports</code></td><td>Access to reports and data exports</td><td>Data warehousing, bulk sync.</td><td>Moderate. Can be used to export bulk datasets.</td></tr><tr><td><code>data-read</code></td><td>Read only access to records and data across all events.</td><td>Querying, two-way integrations.</td><td>High. Reads every register in every event</td></tr><tr><td><code>data-write</code></td><td>Read and write access to records and data across all events.</td><td>Bulk import, REST record injection, two-way integrations.</td><td>Highest. Writes to every register in every event</td></tr><tr><td><code>ops</code></td><td>Full remote control</td><td>Access to administrative APIs</td><td>Highest. Not typically approved for use. </td></tr></tbody></table>

### Managing API keys

System administrators can access the API key management screen to view, create and revoke API keys.

To locate the API key management screen:

1. Sign in as a user with full administrative permission
2. Under your user profile menu, select "API Keys"

On this screen, each service user will be listed.&#x20;

{% hint style="info" %}
If you do not see any service users, contact Datalink or organise your API integration.
{% endhint %}

Under each service user, you can:

* view the current API keys,&#x20;
* view their last use and expiry dates,
* revoke api keys, and
* create new API keys

#### Creating new keys

To create a new API key, click Create, then enter a key name (e.g. "Asset Import 2026-2027"), then click Next. The key will be generated and displayed on screen. This will only be displayed once, so copy it into a secure place. The key is able to be used immediately.  &#x20;

#### Revoking a key

You can revoke an API key by clicking the Revoke button next to the API key listed on screen. It will be revoked immediately. Note that access tokens generated from the last authentication using the key will still be active until they expire (which is within 1 hour).

## Using a User identity (legacy)

{% hint style="warning" %}
This option is provided for compatibility with older software and integrations. We recommend using the **Service Identity** model for new integrations.
{% endhint %}

The User Identity model allows real users to automate their use of the system. All actions are attributed to the real user, and are secured by the user's positions and duty at the time the APIs are run.

### Setting up a user for API access

To set up a user identity for API use:

* Start with a real user account.
* Add the *API User* position to the user. If you do not see the **API User** position, contact Datalink Support to organise it to be set up.
* Set up the user with the required additional positions to access the data interactively. For example, if you need access to data in an event, the user must be on duty for that event in a position that provides access to that data.
* If the user is to access features such as asset import or report generation, then the user will need a position that supports the feature (e.g. an administrative position). For imports and report generation specifically, users only need to be allocated the position and do not need to be on duty.

To authenticate, you will supply the user's username, password and a TOTP MFA code from a generator.

### Using `oauthtool` for CLI-based MFA

The system requires all users authenticate with MFA. This presents a challenge with API integrations using user identities.

The `oauthtool` utility is open source software that can be downloaded using your package manager.

* Debian/Ubuntu: `sudo apt install oathtool`
* MacOS: `brew install oath-toolkit`
* Windows (WSL or Chocolatey): `choco install oath-toolkit`

To generate TOTP codes using `oathtool`, you need the TOTP secret key from Crisisworks. Which can be found by clicking the link "Get code for manual entry" under the QR code when registering the TOTP device.

Next, register the TOTP by entering the following command with your TOTP secret.

```
oathtool --totp -b "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
```

Each time this is run, this command will return a six-digit TOTP code. You can run it once and enter into the system to register the tool with as your user's MFA.

## Obtaining an access token

{% hint style="info" %}
Your API key is used to create a time-limited Access Token for the session, and cannot be used directly in our REST and RPC APIs.
{% endhint %}

Once you have an API key, use the `auth` endpoint to obtain a time-limited access token, which can be used in the REST and RPC APIs.&#x20;

### Fetching an authentication token

To fetch an authentication token, call the `auth` API command and supply the user credentials. Then supply that token to all authenticated API commands using the `Authorization` header to perform the command on behalf of that user.

Authentication tokens are OAuth2 JWT Access Tokens which expire after a short period. Therefore, for recurring use of the API you should store the API key securely at your side and call the `auth` endpoint to fetch a new token.

The `auth` API also supports API keys (recommended) and username/password/MFA (legacy integrations only):

* For Service Identity authentication (machine to machine), generate and use an API key
* For user-based authentication, supply your  `username` and `password`  and `mfaCode`. The POSIX `authtool` utility can be registered as an MFA device to issue TOTP MFA codes.

To call the `auth` API, use the following:

```http
POST https://{{host}}/api/json/auth
Accept: application/json
Content-Type: application/json;charset=UTF-8
X-Site: {{site}}

{
  "version": "1",
  "uuid": "{{uuid}}",
  "platform": "Windows",
  "name": "Sync asset contacts",
  
  # for service identity authentication (recommended)
  "apiKey": "...",
  
  # for user-based authentication (for legacy integrations only)
  "username": "{{username}}",
  "password": "{{password}}",
  "mfaCode": "{{mfaCode}}"
}
```

<table><thead><tr><th width="161.68359375">Parameter</th><th width="124.7578125">Type</th><th width="194.6953125">Mandatory</th><th>Description</th></tr></thead><tbody><tr><td><code>uuid</code></td><td>string</td><td>Yes</td><td>A unique code that represents the connected device. For devices this is the device's UUID code. For servers, this should be the server's URL.</td></tr><tr><td><code>platform</code></td><td>string</td><td>Yes</td><td>A freetext string representing the source of the connection — e.g. Tech One, Pathway, MyApp, Windows, etc.</td></tr><tr><td><code>version</code></td><td>string</td><td>Yes</td><td>The version of the client software — e.g. 11</td></tr><tr><td><code>name</code></td><td>string</td><td>Yes</td><td>The name of the device or integration — e.g. "Asset contact import"</td></tr><tr><td><code>apiKey</code></td><td>string</td><td>Service Identity auth</td><td>Your secret API key</td></tr><tr><td><code>username</code></td><td>string</td><td>User Identity auth (legacy)</td><td>The user username</td></tr><tr><td><code>password</code></td><td>string</td><td>User Identity auth (legacy)</td><td>The user's password</td></tr><tr><td><code>mfaCode</code></td><td>string</td><td>User Identity auth (legacy)</td><td>An user's TOTP MFA code</td></tr></tbody></table>

If the user is successfully authenticated, the command returns a JSON object with the following values:

```json
{
  "status": 200,
  "token": "eyJraWQiOiJCelhSZVwvdW9cL0VUczJjUUJF...",
  "type": "accessToken"
}
```

<table><thead><tr><th width="169.7421875">Key</th><th width="131.8203125">Type</th><th>Description</th></tr></thead><tbody><tr><td>token</td><td>string</td><td>An OAuth2 Access Token which can be used to perform actions on behalf of a nominated user</td></tr><tr><td>status</td><td>int</td><td>200 for success, 400 for invalid intput, 401 for invalid credentials, 500 for internal server errors</td></tr><tr><td>type</td><td>string</td><td>The type of token returned (this will always be 'accessToken')</td></tr></tbody></table>

If the user's credentials are invalid, the server responds with a **401** HTTP error.

```json
{
  "status":401,
  "message":"Invalid user, password or mfaCode"
}
```

The access token will have a 1 hour expiry, so you will need to re-authenticate for each session.

### Using an authentication token

Once you have acquired the auth token, you can use it for all APIs via the `Authorization` header as follows.

```http
GET https://{{host}}/api/json/item/id/1
Accept: application/json
Content-Type: application/json;charset=UTF-8
Authorization: Bearer {{token}}
X-Site: {{site}}
```

{% hint style="info" %}
Both `Authorization` and `X-Site` are required for most API calls.
{% endhint %}

### Treat your secrets securely

The examples in this guide take shortcuts for readability, with the main one being the storage of secrets in environment variables.

For production use:

* API users typically have high degrees of access.
* Treat your API user's key, password and TOTP secret as sensitive secrets.
* Don’t hardcode secrets in scripts — use environment variables or secure vault utilities.

For secure storage options, consider using these utilities such as these.

* [CredentialManager](https://www.powershellgallery.com/packages/CredentialManager) in PowerShell
* [Secrets Manager](https://aws.amazon.com/secrets-manager/) on AWS
* [pass](https://www.passwordstore.org/) on Linux
* Password managers (such as [1Password](https://1password.com)) also offer CLI tools to store secrets

## Examples

### Authenticating using an API Key in BASH

The following simple example shows how to call the `auth` command from a bash script using an API Key.

```bash
# ---- Configuration ----
HOST="api.cw.crisisworks.com"
SITE="sandbox"
UUID="example-uuid-123"
APIKEY="XXXXXXXX" # example only, do not hardcode
CLIENT_NAME="Test Harness"

# ---- Build JSON payload ----
read -r -d '' PAYLOAD <<EOF
{
  "version": "1",
  "uuid": "$UUID",
  "platform": "curl",
  "name": "$CLIENT_NAME",
  "apiKey": "$APIKEY"
}
EOF

# ---- Send authentication request and capture response ----
RESPONSE=$(curl -s -X POST "https://${HOST}/api/json/auth" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "X-Site: ${SITE}" \
  -d "$PAYLOAD")

# ---- Output or process response as needed ----
echo "$RESPONSE"

```

### Authenticating using a user identity with MFA in BASH

The following shell script illustrates how to authenticate with MFA in `bash` and `curl`.

```shell
#!/bin/bash

# ---- Configuration ----
HOST="api.cw.crisisworks.com"
SITE="mysite"
UUID="example-uuid-123"
USERNAME="your.username"
PASSWORD="your.password" # example only, do not hardcode
TOTP_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  # Base32-encoded TOTP secret
CLIENT_NAME="Test Harness"

# ---- Generate current MFA TOTP code using oathtool ----
MFA_CODE=$(oathtool --totp -b "$TOTP_SECRET")

# ---- Build JSON payload ----
read -r -d '' PAYLOAD <<EOF
{
  "version": "1",
  "uuid": "$UUID",
  "platform": "curl",
  "name": "$CLIENT_NAME",
  "username": "$USERNAME",
  "password": "$PASSWORD",
  "mfaCode": "$MFA_CODE"
}
EOF

# ---- Send authentication request and capture response ----
RESPONSE=$(curl -s -X POST "https://${HOST}/api/json/auth" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "X-Site: ${SITE}" \
  -d "$PAYLOAD")

# --- Extract the token using jq ---
TOKEN=$(echo "$RESPONSE" | jq -r '.token')

# --- Check token was retrieved ---
if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
  echo "❌ Failed to retrieve token."
  exit 1
fi
```

Now you can call the authenticated commands using the token.

```shell
# --- Now make some authenticated API calls ---
RESPONSE=$(curl -s -X GET "https://${HOST}/api/json/ping" \
  -H "Accept: application/json" \
  -H "Authorization: $TOKEN" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "X-Site: $SITE")
  
# --- Output the ping response ---
echo $RESPONSE  
```

### Authenticating with MFA in PowerShell

The following example shows how to authenticate in Windows PowerShell.

```shell
# --- Configuration ---
$host     = "api.cw.crisisworks.com"
$site     = "mysite"
$uuid     = "example-uuid-123"
$username = "your.username"
$password = "your.password" # example only, do not hardcode
$totpSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  # Base32-encoded TOTP secret
$clientName = "Test Harness"

# --- Generate MFA code using oathtool ---
# Ensure oathtool is in PATH (e.g., from Chocolatey or WSL)
$mfaCode = & oathtool --totp -b $totpSecret

# --- Prepare request payload ---
$body = @{
    version  = "1"
    uuid     = $uuid
    platform = "curl"
    name     = $clientName
    username = $username
    password = $password
    mfaCode  = $mfaCode
} | ConvertTo-Json -Depth 3

# --- Send POST request to fetch token ---
$response = Invoke-RestMethod -Method Post `
    -Uri "https://$host/api/json/auth" `
    -Headers @{
        "Accept"       = "application/json"
        "Content-Type" = "application/json;charset=UTF-8"
        "X-Site"       = $site
    } `
    -Body $body

# --- Extract the token from the response ---
$token = $response.token

# --- Verify token and use it ---
if (-not $token) {
    Write-Error "❌ Failed to retrieve token."
    exit 1
}
```

Now you can call the other API commands using the token.

```shell
# --- Call the authenticated /ping endpoint ---
$pingResponse = Invoke-RestMethod -Method Get `
    -Uri "https://$host/api/json/ping" `
    -Headers @{
        "Authorization" = $token
        "Accept"        = "application/json"
        "Content-Type"  = "application/json;charset=UTF-8"
        "X-Site"        = $site
    }

# --- Output the ping response ---
$pingResponse
```

### Authenticating in PHP

```php
// Configuration
$host       = "api.cw.crisisworks.com";
$site       = "mysite";
$uuid       = "example-uuid-123";
$username   = "your.username";
$password   = "your.password"; # example only, do not hardcode
$totpSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";  // Base32-encoded TOTP secret
$clientName = "Test Harness";

// Build the payload
$payload = json_encode([
    "version"  => "1",
    "uuid"     => $uuid,
    "platform" => "curl",
    "name"     => $clientName,
    "username" => $username,
    "password" => $password,
    "mfaCode"  => $mfaCode,
]);

// Send the request
[$statusCode, $body] = sendByCurl(
    'POST',
    $url . '/api/json/auth',
    [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json;charset=UTF-8',
    ],
    $payload
);

// Handle the result
if ($statusCode >= 200 && $statusCode < 300) {
    $bodyDecoded = json_decode($body, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Could not parse JSON during auth registration");
    }
} else {
    throw new Exception("Got invalid http status code $statusCode during auth registration");
}

if (!($bodyDecoded['token'] ?? null)) {
    throw new Exception("Did not receive an auth token during registration");
}

// Use this token for future authenticated calls
$token = $bodyDecoded['token'];
```

The above code uses a function to perform the HTTP call

```php
function sendByCurl(string $method, string $url, array $headers, string $payload = null): array
{
    $headersAsStrings = [
        'Content-Length: ' . strlen($payload),
    ];
    foreach ($headers as $key => $val) {
        $headersAsStrings[] = $key . ': ' . $val;
    }

    $ch = curl_init();

    // configuration directives
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // set 30 second timeout on APIs
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 60000);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 60000);

    // set the header, method and payload
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headersAsStrings);
    if (strtoupper((string)$method) === 'GET') {
        // do nothing
    } else {
        if (strtoupper((string)$method) === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
        } else {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
    }
    if ($payload) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    }

    curl_setopt($ch, CURLOPT_ENCODING, ''); // not gzip, deflate

    // Call the URL
    $body = curl_exec($ch);
    $statusCode = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

    // Test the response to ensure valid json
    if ($statusCode === 200) {
        json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $statusCode = 400; // invalid response data
        }
    }
    curl_close($ch);

    return [$statusCode, $body];
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.cw.crisisworks.com/security-and-support/technical-reference/api-reference/authentication.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
