> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 智能体身份验证

## 概述

构建对话式智能体时，可能需要限制特定智能体或对话的访问权限。ElevenLabs 提供多种身份验证机制，确保只有获得授权的用户才能与智能体互动。

## 身份验证方法

ElevenLabs 提供两种主要方法来保护对话式智能体：

#### [签名 URL](#using-signed-urls)

生成临时认证 URL，安全建立客户端连接，无需暴露 API
密钥。

#### [允许列表](#using-allowlists)

限制可连接到智能体的特定域名或主机名。

## 使用签名 URL

对于客户端应用，建议使用签名 URL。该方法可在不暴露 API 密钥的情况下验证用户身份。

> **Note**
>
> 以下指南使用 [JS 客户端](https://www.npmjs.com/package/@elevenlabs/client) 和
> [Python SDK](https://github.com/elevenlabs/elevenlabs-python/)。

### 签名 URL 的工作原理

1. 服务器使用 API 密钥向 ElevenLabs 请求签名 URL。
2. ElevenLabs 生成临时令牌并返回签名 WebSocket URL。
3. 客户端应用使用该签名 URL 建立 WebSocket 连接。
4. 签名 URL 会在 15 分钟后过期。

> **Warning**
>
> 切勿在客户端暴露 ElevenLabs API 密钥。

### 通过 API 生成签名 URL

要获取签名 URL，请使用智能体 ID 向 `get_signed_url` [端点](/docs/zh/eleven-agents/api-reference/conversations/get-signed-url)发起请求：

```python
# Server-side code using the Python SDK
from elevenlabs.client import ElevenLabs
async def get_signed_url():
    try:
        elevenlabs = ElevenLabs(api_key="your-api-key")
        response = await elevenlabs.conversational_ai.conversations.get_signed_url(agent_id="agent_7101k5zvyjhmfg983brhmhkd98n6")
        return response.signed_url
    except Exception as error:
        print(f"Error getting signed URL: {error}")
        raise
```

```javascript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";

// Server-side code using the JavaScript SDK
const elevenlabs = new ElevenLabsClient({ apiKey: "your-api-key" });
async function getSignedUrl() {
  try {
    const response = await elevenlabs.conversationalAi.conversations.getSignedUrl({
      agentId: "agent_7101k5zvyjhmfg983brhmhkd98n6",
    });

    return response.signed_url;
  } catch (error) {
    console.error("Error getting signed URL:", error);
    throw error;
  }
}
```

```bash
curl -X GET "https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=agent_7101k5zvyjhmfg983brhmhkd98n6" \
-H "xi-api-key: your-api-key"
```

curl 响应格式如下：

```json
{
  "signed_url": "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=agent_7101k5zvyjhmfg983brhmhkd98n6&conversation_signature=your-token"
}
```

### 使用签名 URL 连接智能体

从客户端获取服务器生成的签名 URL，并使用该 URL 连接到 WebSocket。

```python
# Client-side code using the Python SDK
from elevenlabs.conversational_ai.conversation import (
    Conversation,
    AudioInterface,
    ClientTools,
    ConversationInitiationData
)
import os
from elevenlabs.client import ElevenLabs
api_key = os.getenv("ELEVENLABS_API_KEY")

elevenlabs = ElevenLabs(api_key=api_key)

conversation = Conversation(
  client=elevenlabs,
  agent_id=os.getenv("AGENT_ID"),
  requires_auth=True,
  audio_interface=AudioInterface(),
  config=ConversationInitiationData()
)

async def start_conversation():
  try:
    signed_url = await get_signed_url()
    conversation = Conversation(
      client=elevenlabs,
      url=signed_url,
    )

    conversation.start_session()
  except Exception as error:
    print(f"Failed to start conversation: {error}")

```

```javascript
// Client-side code using the JavaScript SDK
import { Conversation } from "@elevenlabs/client";

async function startConversation() {
  try {
    const signedUrl = await getSignedUrl();
    const conversation = await Conversation.startSession({
      signedUrl,
    });

    return conversation;
  } catch (error) {
    console.error("Failed to start conversation:", error);
    throw error;
  }
}
```

### 签名 URL 过期

签名 URL 的有效期为 15 分钟。对话会话可以持续更久，但必须在 15 分钟内发起对话。

## 使用允许列表

允许列表可根据来源域名限制对话式智能体的访问权限，确保只有来自已批准域名的请求才能连接到智能体。

### 允许列表的工作原理

1. 为智能体配置已批准主机名列表。
2. 客户端尝试连接时，ElevenLabs 会检查请求来源是否与允许的主机名匹配。
3. 如果来源位于允许列表中，则允许连接；否则将被拒绝。

### 配置允许列表

允许列表是智能体身份验证设置的一部分。最多可指定 10 个唯一主机名连接到智能体。

### 示例：设置允许列表

#### 通过控制台配置

在控制台中打开智能体，进入 **安全** 选项卡。将每个已批准的主机名（例如 `example.com`、`app.example.com`、`localhost:3000`）添加到允许列表。

#### 通过 CLI 配置

#### 拉取智能体

```bash
elevenlabs agents pull --agent "<agent-name>"
```

#### 编辑智能体配置

在 `agent_configs/<agent-name>.json` 中设置 `platform_settings.auth`：

```json
{
  "platform_settings": {
    "auth": {
      "enable_auth": false,
      "allowlist": [
        { "hostname": "example.com" },
        { "hostname": "app.example.com" },
        { "hostname": "localhost:3000" }
      ]
    }
  }
}
```

#### 推送更改

```bash
elevenlabs agents push --agent "<agent-name>"
```

#### 通过 API 配置

```python
from elevenlabs.client import ElevenLabs
import os
from elevenlabs.types import *

api_key = os.getenv("ELEVENLABS_API_KEY")
elevenlabs = ElevenLabs(api_key=api_key)

agent = elevenlabs.conversational_ai.agents.create(
  conversation_config=ConversationalConfig(
    agent=AgentConfig(
      first_message="Hi. I'm an authenticated agent.",
    )
  ),
  platform_settings=AgentPlatformSettingsRequestModel(
  auth=AuthSettings(
    enable_auth=False,
    allowlist=[
      AllowlistItem(hostname="example.com"),
      AllowlistItem(hostname="app.example.com"),
      AllowlistItem(hostname="localhost:3000")
      ]
    )
  )
)
```

```javascript
async function createAuthenticatedAgent(client) {
  try {
    const agent = await elevenlabs.conversationalAi.agents.create({
      conversationConfig: {
        agent: {
          firstMessage: "Hi. I'm an authenticated agent.",
        },
      },
      platformSettings: {
        auth: {
          enableAuth: false,
          allowlist: [
            { hostname: 'example.com' },
            { hostname: 'app.example.com' },
            { hostname: 'localhost:3000' },
          ],
        },
      },
    });

    return agent;
  } catch (error) {
    console.error('Error creating agent:', error);
    throw error;
  }
}
```

## 选择身份验证方法

每个智能体配置一种身份验证方法：

1. 对经过身份验证的客户端会话使用签名 URL（`enable_auth`）。
2. 对基于主机名的访问控制使用允许列表（`allowlist`）。

不要在同一智能体上同时配置签名 URL 和允许列表。请选择与部署模式相符的方法。

### 示例：仅使用签名 URL

使用不含 `allowlist` 的 `enable_auth`：

```python
from elevenlabs.client import ElevenLabs
import os
from elevenlabs.types import *

api_key = os.getenv("ELEVENLABS_API_KEY")
elevenlabs = ElevenLabs(api_key=api_key)

agent = elevenlabs.conversational_ai.agents.create(
  conversation_config=ConversationalConfig(
    agent=AgentConfig(
      first_message="Hi. I require a signed URL.",
    )
  ),
  platform_settings=AgentPlatformSettingsRequestModel(
    auth=AuthSettings(
      enable_auth=True
    )
  )
)
```

```javascript
async function createSignedUrlAgent(client) {
  try {
    const agent = await client.conversationalAi.agents.create({
      conversationConfig: {
        agent: {
          firstMessage: "Hi. I require a signed URL.",
        },
      },
      platformSettings: {
        auth: {
          enableAuth: true,
        },
      },
    });

    return agent;
  } catch (error) {
    console.error("Error creating agent:", error);
    throw error;
  }
}
```

### 示例：仅使用允许列表

使用 `allowlist`，不启用签名 URL：

```python
from elevenlabs.client import ElevenLabs
import os
from elevenlabs.types import *

api_key = os.getenv("ELEVENLABS_API_KEY")
elevenlabs = ElevenLabs(api_key=api_key)

agent = elevenlabs.conversational_ai.agents.create(
  conversation_config=ConversationalConfig(
    agent=AgentConfig(
      first_message="Hi. I only accept approved hostnames.",
    )
  ),
  platform_settings=AgentPlatformSettingsRequestModel(
    auth=AuthSettings(
      allowlist=[
        AllowlistItem(hostname="example.com"),
        AllowlistItem(hostname="app.example.com"),
      ]
    )
  )
)
```

```javascript
async function createAllowlistAgent(client) {
  try {
    const agent = await client.conversationalAi.agents.create({
      conversationConfig: {
        agent: {
          firstMessage: "Hi. I only accept approved hostnames.",
        },
      },
      platformSettings: {
        auth: {
          allowlist: [{ hostname: "example.com" }, { hostname: "app.example.com" }],
        },
      },
    });

    return agent;
  } catch (error) {
    console.error("Error creating agent:", error);
    throw error;
  }
}
```

## 常见问题

#### 可以让多个用户使用同一个签名 URL 吗？

可以，但建议为每个用户会话生成新的签名 URL。

#### 如果签名 URL 在对话过程中失效，会怎样？

如果签名 URL 过期（15 分钟后），使用该签名 URL 创建的任何 WebSocket 连接都**不会**关闭，但尝试使用该签名 URL 创建新连接会失败。

#### 可以限制特定用户访问吗？

签名 URL 机制仅验证请求是否来自授权来源。要限制特定用户访问，请在请求签名 URL 前，在应用中实现用户身份验证。

#### 可生成的签名 URL 数量有限制吗？

可生成的签名 URL 数量没有具体限制。

#### 允许列表如何处理子域名？

允许列表会精确匹配主机名。如果希望同时允许某个域名及其子域名，需要分别添加每一个（例如 "example.com" 和 "app.example.com"）。

#### 需要同时使用两种身份验证方法吗？

不需要。为每个智能体配置签名 URL 或允许列表之一即可。对于客户端应用，建议默认使用签名 URL。

#### 还应实施哪些安全措施？

除签名 URL 和允许列表外，还可以考虑实施：

* 请求签名 URL 前进行用户身份验证
* 对 API 请求实施速率限制
* 监控是否存在可疑的使用模式
* 妥善处理身份验证失败的错误