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

# API Authentication Guide

> Complete guide for authenticating with the UTMStack API using Bearer Token or API Key methods. Learn how to access secured endpoints and find official API documentation.

## Authentication Methods

UTMStack API supports two authentication methods:

1. **Bearer Token Authentication**: Uses username/password to obtain a JWT Bearer token for API requests
2. **API Key Authentication**: Uses managed API keys created through UTMStack Settings

Choose the authentication method that best fits your use case and security requirements.

***

## Method 1: Bearer Token Authentication

### Step 1: Authentication Request

<Tip>
  Use the **/api/authenticate** endpoint to log in and receive a Bearer token.
</Tip>

> 🔧 Request Example:

```
curl -X POST https://demo.utmstack.com/api/authenticate \
-H "Content-Type: application/json" \
-d '{"username":"demo","password":"your_password"}'
```

<Note>
  Make sure to replace the credentials **(username and password)** with the actual user **credentials for your environment**.
</Note>

### Step 2: Parse the Response

> The response will be a JSON object containing the Bearer token, usually under the key id\_token or similar, for example:

```
{
  "authenticated":true,
  "id_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6..."
}
```

### Step 3: Use the Bearer Token

> Include the token in the Authorization header when making requests to protected endpoints.

<Tip>
  Use the **/api/elasticsearch/search** endpoint to test your Bearer token authentication.
</Tip>

> **Request Example:**

```
curl -X 'POST' \
  'https://demo.utmstack.com/api/elasticsearch/search?page=1&size=25&top=100000000&indexPattern=alert-*&sort=@timestamp,desc' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkZW1vIiwiYXV0aCI6IlJPTEVfQURNSU4sU...' \
  -d '[
    {
      "field": "status",
      "operator": "IS",
      "value": 2
    },
    {
      "field": "tags",
      "operator": "IS_NOT",
      "value": "False positive"
    },
    {
      "field": "@timestamp",
      "operator": "IS_BETWEEN",
      "value": [
        "now-7d",
        "now"
      ]
    }
  ]'
```

> **Response:**

```
{
  "severity": 3,
  "regDateRulebot": null,
  "severityLabel": "High",
  "notes": "",
  "dataType": "alertEventLog",
  "destination": {
    "country": "India",
    "accuracyRadius": 5,
    "city": "New Delhi",
    "ip": "122.176.80.250",
    "coordinates": [
      28.6320,
      77.2202
    ]
  },
  "port": 63725,
  "countryCode": "IN",
  "subProtocolCategory": "false",
  "alertEventDetailCateg": "utmstack.demo",
  "isSatelliteProvider": false,
  "ago": "Thatti Airtel Ltd. , Telangela Services",
  "user": "Administrator",
  "san": 24505
}
```

<Warning>
  What happens when you don't include the Authorization header when making requests to protected endpoints.
</Warning>

> **Request without Authorization:**

```
curl -X 'POST' \
  'https://demo.utmstack.com/api/elasticsearch/search?page=1&size=25&top=100000000&indexPattern=alert-*&sort=@timestamp,desc' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "field": "status",
      "operator": "IS",
      "value": 2
    },
    {
      "field": "tags",
      "operator": "IS_NOT",
      "value": "False positive"
    },
    {
      "field": "@timestamp",
      "operator": "IS_BETWEEN",
      "value": [
        "now-7d",
        "now"
      ]
    }
  ]'
```

> **Response:**

```
{
  "timestamp": "2025-04-16T16:26:35.664+00:00",
  "status": 401,
  "error": "Unauthorized",
  "path": "/api/elasticsearch/search"
}
```

***

## Method 2: API Key Authentication

<Info>
  API Keys provide a secure alternative to Bearer tokens for programmatic access. They are ideal for integrations, automation scripts, and third-party applications.
</Info>

### Step 1: Create an API Key

Before you can use API Key authentication, you need to create an API key in UTMStack:

<Steps>
  <Step title="Navigate to Settings">
    Go to **Settings** > **API Keys** in your UTMStack interface.
  </Step>

  <Step title="Create New API Key">
    Click **Create API Key** and configure:

    * **Name**: Descriptive name for your integration
    * **Expires At**: Set expiration date
    * **Allowed IPs**: Add IP addresses or CIDR ranges (recommended for security)
  </Step>

  <Step title="Copy Your API Key">
    After creation, **copy the API key immediately** - it will only be shown once!

    <Warning>
      Store the API key securely. You cannot retrieve it again after closing the dialog.
    </Warning>
  </Step>
</Steps>

<Card title="Complete API Key Management Guide" icon="key" href="/v11/apidoc/api-keys">
  For detailed instructions on creating, managing, and securing API keys, see the API Keys Management documentation.
</Card>

***

### Step 2: Use the API Key in Requests

Include your API key as a Bearer token in the `Authorization` header:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X 'POST' \
    'https://demo.utmstack.com/api/elasticsearch/search?page=1&size=25&top=100000000&indexPattern=alert-*&sort=@timestamp,desc' \
    -H 'accept: */*' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY_HERE' \
    -d '[
      {
        "field": "status",
        "operator": "IS",
        "value": 2
      },
      {
        "field": "tags",
        "operator": "IS_NOT",
        "value": "False positive"
      },
      {
        "field": "@timestamp",
        "operator": "IS_BETWEEN",
        "value": [
          "now-7d",
          "now"
        ]
      }
    ]'
  ```

  ```python Python theme={null}
  import requests
  import os

  # Load API key from environment variable
  api_key = os.environ.get('UTMSTACK_API_KEY')

  url = "https://demo.utmstack.com/api/elasticsearch/search"
  headers = {
      "Authorization": f"Bearer {api_key}",
      "Content-Type": "application/json"
  }

  params = {
      "page": 1,
      "size": 25,
      "top": 100000000,
      "indexPattern": "alert-*",
      "sort": "@timestamp,desc"
  }

  filters = [
      {
          "field": "status",
          "operator": "IS",
          "value": 2
      },
      {
          "field": "tags",
          "operator": "IS_NOT",
          "value": "False positive"
      },
      {
          "field": "@timestamp",
          "operator": "IS_BETWEEN",
          "value": ["now-7d", "now"]
      }
  ]

  response = requests.post(url, headers=headers, params=params, json=filters)
  print(response.json())
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  // Load API key from environment variable
  const apiKey = process.env.UTMSTACK_API_KEY;

  const config = {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    params: {
      page: 1,
      size: 25,
      top: 100000000,
      indexPattern: 'alert-*',
      sort: '@timestamp,desc'
    }
  };

  const filters = [
    {
      field: 'status',
      operator: 'IS',
      value: 2
    },
    {
      field: 'tags',
      operator: 'IS_NOT',
      value: 'False positive'
    },
    {
      field: '@timestamp',
      operator: 'IS_BETWEEN',
      value: ['now-7d', 'now']
    }
  ];

  axios.post('https://demo.utmstack.com/api/elasticsearch/search', filters, config)
    .then(response => console.log(response.data))
    .catch(error => console.error(error));
  ```

  ```powershell PowerShell theme={null}
  # Load API key from environment variable
  $apiKey = $env:UTMSTACK_API_KEY

  $headers = @{
      "Authorization" = "Bearer $apiKey"
      "Content-Type" = "application/json"
  }

  $params = @{
      page = 1
      size = 25
      top = 100000000
      indexPattern = "alert-*"
      sort = "@timestamp,desc"
  }

  $filters = @(
      @{
          field = "status"
          operator = "IS"
          value = 2
      },
      @{
          field = "tags"
          operator = "IS_NOT"
          value = "False positive"
      },
      @{
          field = "@timestamp"
          operator = "IS_BETWEEN"
          value = @("now-7d", "now")
      }
  )

  $response = Invoke-RestMethod -Uri "https://demo.utmstack.com/api/elasticsearch/search" `
      -Method Post `
      -Headers $headers `
      -Body ($params | ConvertTo-Json) `
      -ContentType "application/json"

  $response | ConvertTo-Json
  ```
</CodeGroup>

<Note>
  The API key is used exactly like a Bearer token - just replace the JWT token with your API key in the Authorization header.
</Note>

***

### Step 3: API Key Response

When using a valid API key, you'll receive the same successful response as with JWT authentication:

```json theme={null}
{
  "severity": 3,
  "regDateRulebot": null,
  "severityLabel": "High",
  "notes": "",
  "dataType": "alertEventLog",
  "destination": {
    "country": "India",
    "accuracyRadius": 5,
    "city": "New Delhi",
    "ip": "122.176.80.250",
    "coordinates": [28.6320, 77.2202]
  },
  "port": 63725,
  "countryCode": "IN",
  "subProtocolCategory": "false",
  "alertEventDetailCateg": "utmstack.demo",
  "isSatelliteProvider": false,
  "ago": "Thatti Airtel Ltd. , Telangela Services",
  "user": "Administrator",
  "san": 24505
}
```

***

### API Key Best Practices

<AccordionGroup>
  <Accordion title="Store Keys Securely" icon="shield-check">
    * Never hardcode API keys in source code
    * Use environment variables or secret management systems
    * Avoid committing keys to version control
    * Store in encrypted configuration or password managers
  </Accordion>

  <Accordion title="Restrict by IP Address" icon="network-wired">
    Always configure allowed IP addresses when creating API keys:

    * Limits access to specific servers or networks
    * Prevents unauthorized use if key is compromised
    * Use CIDR notation for IP ranges
  </Accordion>

  <Accordion title="Set Appropriate Expiration" icon="clock">
    * Use shorter expiration periods for development (30-90 days)
    * Set longer periods for production (6-12 months)
    * Rotate keys before expiration
    * Remove or regenerate unused keys
  </Accordion>

  <Accordion title="Monitor and Audit" icon="chart-line">
    * Regularly review active API keys in Settings
    * Check last used timestamps
    * Monitor for unexpected access patterns
    * Set up alerts for failed authentication attempts
  </Accordion>

  <Accordion title="One Key Per Integration" icon="puzzle-piece">
    Create separate API keys for different:

    * Applications or services
    * Environments (dev, staging, production)
    * Teams or departments

    This limits impact if a key is compromised.
  </Accordion>
</AccordionGroup>

***

## Authentication Methods Comparison

| Feature        | Bearer Token (JWT)                                  | API Key                                    |
| -------------- | --------------------------------------------------- | ------------------------------------------ |
| **Use Case**   | User-based authentication, interactive applications | Server-to-server, automation, integrations |
| **Creation**   | Obtained via login credentials                      | Created in Settings > API Keys             |
| **Lifetime**   | Short-lived, expires after session                  | Long-lived, custom expiration date         |
| **Security**   | User-specific, session-based                        | Key-specific, can be restricted by IP      |
| **Revocation** | Automatic on logout                                 | Manual deletion or expiration              |
| **Best For**   | Web applications, user sessions                     | Automated scripts, CI/CD, third-party apps |
| **Management** | Automatic                                           | Manual via Settings UI                     |

<Tip>
  **Recommendation**:

  * Use **Bearer Token** for user-facing applications and interactive sessions
  * Use **API Key** for backend integrations, automation scripts, and long-running services
</Tip>

***

## Official API Documentation

UTMStack provides two official resources where developers can explore and interact with the API:

### Interactive Swagger UI (Demo Instance)

For hands-on testing and live API interaction, you can explore the Swagger UI provided by the public UTMStack demo instance:

[https://demo.utmstack.com/swagger-ui/index.html](https://demo.utmstack.com/swagger-ui/index.html)

<Note>
  Each client instance has its own unique Swagger URL, based on how their environment is configured.
</Note>

Examples:

* `https://<your-company>.utmstack.com/swagger-ui/index.html`
* `https://utmstack.<your-domain>.com/swagger-ui/index.html`

<Tip>
  These tools make it easy to test endpoints, view required parameters, and understand the behavior of the platform's APIs.
</Tip>
