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

# 1. Authentication with username and password

> [!WARNING]
>
> You are viewing the documentation of release 26.1, which is no longer the current one. [Go to the documentation of the current release 26.2](https://developers.circularo.com/).

## Session-based Authentication Overview

Session-based authentication is the standard method for authenticating users in the Circularo system. It provides a secure way to access the API and perform operations on behalf of the authenticated user.

**Key features:**

* Simple username and password authentication
* Session tokens valid for 30 days by default
* Required for most API operations
* Support for Multi-Factor Authentication (MFA) when enabled

**Security considerations:**

* Store session tokens securely and never expose them in client-side code
* Implement proper token management including logout when sessions are no longer needed
* For server-to-server integrations, consider using API tokens instead

## Step 1 - Authenticate user with username and password

Authenticates a user with their credentials and creates a new session. This is the first step in any API workflow that requires authentication.

* Provides a session token that must be included in subsequent API requests
* Session tokens are valid for 30 days by default
* For multi-factor authentication (MFA) enabled accounts, additional verification steps may be required
* Optional "tenant" parameter can be used to explicitly specify the target tenant, though usually not required as the system automatically selects the correct tenant based on the host header

> [!NOTE]
>
> If your account has Multi-Factor Authentication (MFA) enabled, the token will be returned in a locked state and must be unlocked using the appropriate authentication factor before it can be used.

**Endpoint**

```http theme={null}
POST /login
```

**Request**

```http theme={null}
POST /login

Content-Type: application/json

{
  "name": "mary.griffin@circularo.com",
  "password": "#32Password1!",
  "returnToken": true
}
```

**Response**

```json theme={null}
{
  "logged": true,
  "isUnlocked": true,
  "token": "Jf93lomzYdnv7AGeRZlEZbtNrRvd8vj0s3PWjhAXgLIkIxnOUmTqZi1tRz6352HV",
  "tenant": "default",
  "user": {
    ...
  },
  "settings": {
    ...
  },
  "rights": [
    ...
  ],
  ...
}
```

The response contains the following important properties:

* **token** - Located at `token` in the response.
  * The authentication token that should be included in subsequent API requests. This token identifies your session and provides access to authorized resources.
  * Example value: `Jf93lomzYdnv7AGeRZlEZbtNrRvd8vj0s3PWjhAXgLIkIxnOUmTqZi1tRz6352HV`

Authentication successful. The response includes a session token that should be included in all subsequent API requests.

* The token should be passed as a query parameter (?token=YOUR\_TOKEN) in subsequent requests
* The token is valid for 30 days from creation
* For security reasons, store this token securely and do not expose it in client-side code

> [!WARNING]
>
> Session tokens should not be shared between different applications or users. Each client should obtain its own token.

## Step 2 - Test the session token by retrieving available documents *(Optional)*

This endpoint demonstrates how to use your session token to perform an actual operation - in this case, searching for available documents in the system.

* The session token is passed in the query parameters
* The search operation returns documents the authenticated user has access to
* This pattern applies to all token protected API endpoints - include your session token in each request

> [!NOTE]
>
> This is a practical example of how to use your session token for API operations. Do not call this endpoint if you don't wish to perform a search operation.

> [!WARNING]
>
> Circularo doesn't support Bearer Token authentication. Specify the token as the query parameter instead.

**Endpoint**

```http theme={null}
POST /search
```

**Request**

```http theme={null}
POST /search?token=Jf93lomzYdnv7AGeRZlEZbtNrRvd8vj0s3PWjhAXgLIkIxnOUmTqZi1tRz6352HV

Content-Type: application/json

{
  "from": 0,
  "size": 10
}
```

**Response**

```json theme={null}
{
  "from": 0,
  "total": 224,
  "results": [
    {
      "documentId": "d29ad103-4f1b-4aba-adfc-c1fb1eb83b9f",
      ...
    },
    ...
  ],
  "users": {
    ...
  },
  ...
}
```

The search operation was successful, demonstrating that your session token is working correctly.

The response includes a list of documents that the authenticated user has access to.

## Step 3 - Terminate the session *(Optional)*

Invalidates the current session token, effectively logging the user out of the system. This is an important security practice to prevent unauthorized access after a session is no longer needed.

* Invalidates the token provided in the request
* Prevents the token from being used for any future API requests
* Should be called when a session is no longer needed
* Does not affect other active sessions for the same user

> [!NOTE]
>
> This endpoint only invalidates the specific token provided in the request. Other active sessions for the same user will remain valid.

**Endpoint**

```http theme={null}
GET /logout
```

**Request**

```http theme={null}
GET /logout?token=Jf93lomzYdnv7AGeRZlEZbtNrRvd8vj0s3PWjhAXgLIkIxnOUmTqZi1tRz6352HV
```

The session has been successfully terminated. The token is now invalid and cannot be used for further API requests.

***

## Session Authentication Summary

Session-based authentication provides a secure way to access the Circularo API:

* Authentication is performed using username (email) and password credentials
* The resulting session token must be included in all subsequent token protected API requests
* Session tokens are valid for 30 days by default
* Always terminate sessions with the logout endpoint when they are no longer needed
* For server-to-server integrations, consider using API tokens instead

### Example Authentication Flow

> [!NOTE]
>
> See our OpenAPI documentation to learn about the full set of API endpoints and parameters.

> [!NOTE]
>
> Please use proper exception handling and function decomposition in your own code. The code is provided for illustrative purposes only and is not intended for production use.

```javascript theme={null}
// Basic authentication flow
const URL = "https://sandbox.circularo.com";
const API_PATH = "/api/v1";

const name = "YOUR_NAME/EMAIL";
const password = "YOUR_PASSWORD";

let token;

try {
    // Step 1: Login to get session token
    const loginResponse = await fetch(`${URL}${API_PATH}/login`, {
        method: 'POST',
        body: JSON.stringify({
            name,
            password,
            returnToken: true
            // tenant: "custom"  // Optional: Only needed for targeting a specific tenant
        }),
        headers: { 'Content-Type': 'application/json' }
    });
    if (!loginResponse.ok) {
        throw new Error(`Login failed: ${loginResponse.status} ${loginResponse.statusText}`);
    }

    const loginData = await loginResponse.json();
    if (!loginData.logged) {
        throw new Error('Authentication failed');
    }
    if (!loginData.isUnlocked) {
        console.log('MFA required: Token is locked and requires additional authentication');
        // Handle MFA challenge here
    }
    token = loginData.token;

    // Step 2: Use the token (illustrative purpose)
    const searchResponse = await fetch(`${URL}${API_PATH}/search?token=${token}`, {
        method: 'POST',
        body: JSON.stringify({ from: 0, size: 10 }),
        headers: { 'Content-Type': 'application/json' }
    });
    if (!searchResponse.ok) {
        throw new Error(`Search failed: ${searchResponse.status} ${searchResponse.statusText}`);
    }
    const searchResults = await searchResponse.json();

    // Step 3: Logout when done
    const logoutResponse = await fetch(`${URL}${API_PATH}/logout?token=${token}`);
    if (!logoutResponse.ok) {
        throw new Error(`Logout failed: ${logoutResponse.status} ${logoutResponse.statusText}`);
    }
    console.log('Successfully logged out');

} catch (error) {
    console.error('Error in authentication flow:', error.message);

    // Always try to logout if we have a token, even if other operations failed
    if (token) {
        try {
            const logoutResponse = await fetch(`${URL}${API_PATH}/logout?token=${token}`);
            if (!logoutResponse.ok) {
                throw new Error(`Logout failed: ${logoutResponse.status} ${logoutResponse.statusText}`);
            }
        } catch (logoutError) {
            console.error('Failed to logout:', logoutError.message);
        }
    }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.