> 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では、会話型エージェントを保護する主な方法を2つ提供しています：

#### [署名付きURL](#using-signed-urls)

APIキーを公開せずに、安全なクライアント側接続用の一時的な認証URLを生成します。

#### [許可リスト](#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/ja/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つ設定します：

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;
  }
}
```

### 例：許可リストのみ

署名付きURLを有効にせず、`allowlist`を使用します：

```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リクエストのレート制限
* 不審なパターンを検出するための使用状況監視
* 認証失敗時の適切なエラー処理