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

# Authentication

> Secure user authentication for embedded agents in SDK 3

## Overview

The Mindset AI SDK 3 uses token-based authentication to link client-side sessions to user accounts within the Mindset AI platform. This authentication mechanism ensures secure, seamless integration of user sessions with your embedded agents.

The authentication process handles two scenarios automatically:

**Existing users:** If the user already exists in Mindset AI, the authentication process generates a token that links the current session to their existing account. This provides continuity for returning users.

**New users:** If the user doesn't exist, the system automatically creates a new user account using the provided identifier (email or external ID) and generates an authentication token. This streamlines onboarding without manual intervention.

The authentication token serves as the key to accessing SDK features while maintaining user-specific context, conversation history, and preferences.

<Warning>
  **Server-Side Only:** Authentication must be handled server-side to protect your API key and maintain security. Never expose API keys in client-side code.
</Warning>

## How Authentication Works

<Steps>
  <Step title="User initiates session">
    Your application captures user identification (email or external ID)
  </Step>

  <Step title="Server requests token">
    Your server makes a secure POST request to Mindset AI's authentication endpoint with user details
  </Step>

  <Step title="Token generation">
    Mindset AI validates the request, creates or links the user account, and returns an authentication token
  </Step>

  <Step title="Client-side initialization">
    Your client-side code uses the token to initialize the SDK and establish the user session
  </Step>
</Steps>

## Generate Authentication Token

Make a secure server-side HTTP POST request to the Mindset AI authentication endpoint to generate an authentication token.

### Endpoint

```
POST https://MINDSET-API-HOST/api/v1/appuid/YOUR-APP-UID/sdkusers/auth
```

### Headers

| Header         | Value                  | Description                                                    |
| -------------- | ---------------------- | -------------------------------------------------------------- |
| `Content-Type` | `application/json`     | Required                                                       |
| `x-api-key`    | `YOUR-MINDSET-API-KEY` | Your Mindset AI API key (manage in Developer Tools → API Keys) |

<Note>
  API keys are managed in the Agent Management Studio under **Developer Tools → API Keys**.
</Note>

### Request Body

The request body must include user identification using **either** `externalId` **or** `userEmail` (not both).

| Parameter     | Type   | Required      | Description                                                                     |
| ------------- | ------ | ------------- | ------------------------------------------------------------------------------- |
| `externalId`  | String | Conditional\* | Unique identifier for the user in your system                                   |
| `userEmail`   | String | Conditional\* | Email address of the user                                                       |
| `name`        | String | Optional      | Display name for the user (used when creating new accounts)                     |
| `accountUids` | Array  | Optional      | Array of Mindset AI account UIDs to grant this user access to restricted agents |

<Warning>
  **`*You must provide either externalId OR userEmail, but not both.`** Requests with neither or both will fail.
</Warning>

### Request Examples

**Using external ID (recommended):**

```json theme={null}
{
  "name": "John Smith",
  "externalId": "user-x123456"
}
```

**Using email address:**

```json theme={null}
{
  "name": "Jane Doe",
  "userEmail": "jane.doe@example.com"
}
```

**With account access:**

```json theme={null}
{
  "externalId": "user-x123456",
  "accountUids": ["account-uid-1", "account-uid-2"]
}
```

<Tip>
  **Best practice:** Use `externalId` to control what personally identifiable information (PII) you share with Mindset AI while maintaining user identity across sessions.
</Tip>

### Response

On successful authentication, the API returns an authentication token:

```json theme={null}
{
  "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

Use this token when initializing the SDK on the client side.

## User Management

### How User Accounts Work

When you provide a user identifier to Mindset AI:

1. **Lookup:** The API checks if a user with that identifier already exists
2. **Create or Link:** If the user doesn't exist, a new account is created and linked to the identifier
3. **Token Generation:** An authentication token is generated for this user
4. **Session Continuity:** Returning users automatically access their previous conversation threads and context

### User Identification Best Practices

**`Use externalId (recommended):`**

* Gives you strict control over what PII you share with Mindset AI
* Allows cross-referencing user activity with your platform
* Can be any unique string that identifies the user in your system

**`Using userEmail:`**

* Email addresses are modified to make them unique to your application
* Mindset AI never sends emails to these addresses
* The email serves purely as an identification string

### Account Membership

The optional `accountUids` parameter lets you grant users access to restricted agents automatically during authentication.

**When to use this:**

* You have agents with restricted access (not public to all users)
* You want to control which users can interact with specific agents
* You're implementing role-based or tier-based agent access

For more details, see [Agent Access Granted by Agent Sessions](https://docs.mindset.ai/deploy/sdk3/sdk3-best-practices#agent-access-granted-by-agent-sessions).

## Server-Side Implementation

### Node.js Example

Here's how to implement authentication in Node.js:

```javascript theme={null}
const YOUR_MINDSET_API_KEY = 'YOUR-MINDSET-API-KEY';
const MINDSET_API_HOST = 'MINDSET-API-HOST';
const YOUR_APP_UID = 'YOUR-APP-UID';

const fetch = require('node-fetch');

const requestBody = {
  externalId: 'user-x123456',
  name: 'John Smith' // optional
};

fetch(`https://${MINDSET_API_HOST}/api/v1/appuid/${YOUR_APP_UID}/sdkusers/auth`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': YOUR_MINDSET_API_KEY
  },
  body: JSON.stringify(requestBody)
})
.then(response => response.json())
.then(data => {
  console.log('Authentication Token:', data.authToken);
  // Pass this token to your client-side SDK initialization
})
.catch((error) => {
  console.error('Authentication Error:', error);
});
```

### Integration Pattern

1. **Capture user identity** in your application (email, user ID, etc.)
2. **Call authentication endpoint** from your server with user details
3. **Receive authentication token** from Mindset AI
4. **Pass token to client** securely (never log or expose it)
5. **Initialize SDK** on client side using the token

## Security Considerations

### API Key Protection

<Warning>
  **Keep your API key confidential.** Store it securely in environment variables or secret management systems. Never expose it in client-side code, version control, or logs.
</Warning>

**Best practices:**

* Store API keys in environment variables
* Use secret management services (AWS Secrets Manager, Azure Key Vault, etc.)
* Rotate keys periodically
* Never commit keys to version control
* Use different keys for development and production

### Authentication Token Security

**Handle tokens securely:**

* Transmit tokens over HTTPS only
* Store tokens securely on the client (memory, secure storage)
* Implement token refresh mechanisms for long-lived sessions
* Clear tokens when users log out

**Never:**

* Log tokens to console or files
* Store tokens in localStorage without encryption
* Share tokens between users
* Transmit tokens in URL parameters

## API Reference

For complete API documentation including error codes, rate limits, and advanced parameters, see the [SDK Users API documentation](https://docs.mindset.ai/deploy/api/sdkusers-api).

## Migrate to SDK 3 Authentication

If you're currently using SDK 2 authentication, you'll need to migrate to SDK 3's authentication flow.

<Note>
  **Check if you need to migrate:** If your code uses the legacy endpoint `https://MINDSET-API-HOST/api-authenticate-embedded-user`, you need to migrate.
</Note>

### Migration Steps

<Steps>
  <Step title="Generate new API key">
    In Agent Management Studio, navigate to **Developer Tools → API Keys** and generate a new API key.
  </Step>

  <Step title="Update authentication endpoint">
    Replace the legacy endpoint with the new SDK 3 endpoint:

    ```
    POST https://MINDSET-API-HOST/api/v1/appuid/YOUR-APP-UID/sdkusers/auth
    ```
  </Step>

  <Step title="Update request format">
    Update your request body to use the new parameter format:

    ```json theme={null}
    {
      "name": "User Name",        // optional
      "externalId": "user-123",   // use either externalId
      "userEmail": "user@example.com"  // or userEmail (not both)
    }
    ```
  </Step>

  <Step title="Update headers">
    Use the new API key in the `x-api-key` header:

    ```json theme={null}
    {
      "Content-Type": "application/json",
      "x-api-key": "YOUR-MINDSET-API-KEY"
    }
    ```
  </Step>

  <Step title="Test authentication flow">
    Verify that your server successfully receives authentication tokens and your client can initialize the SDK.
  </Step>
</Steps>

### Key Changes from SDK 2

| Aspect              | SDK 2 (Legacy)                    | SDK 3 (Current)                               |
| ------------------- | --------------------------------- | --------------------------------------------- |
| Endpoint            | `/api-authenticate-embedded-user` | `/api/v1/appuid/{YOUR-APP-UID}/sdkusers/auth` |
| API Key Header      | Custom format                     | `x-api-key`                                   |
| User Identification | Email only                        | `externalId` or `userEmail`                   |
| API Key Management  | Legacy system                     | Developer Tools → API Keys                    |

For complete migration guidance, see the [SDK 3 Migration Guide](https://docs.mindset.ai/deploy/sdk3/sdk3-migration).

## Troubleshooting

### Authentication request fails with 401

**Possible causes:**

* Invalid or missing API key
* API key is from wrong environment (dev key in production)
* API key has been revoked

**Solution:** Verify your API key in Agent Management Studio under Developer Tools → API Keys. Generate a new key if needed.

### Authentication request fails with 400

**Possible causes:**

* Missing both `externalId` and `userEmail`
* Provided both `externalId` and `userEmail`
* Invalid request body format

**Solution:** Ensure you provide exactly one user identifier (`externalId` OR `userEmail`) in valid JSON format.

### Token works initially but fails later

**Possible causes:**

* Token has expired
* User account has been disabled
* Network connectivity issues

**Solution:** Implement token refresh logic. Verify the user account is active in Agent Management Studio.

***
