> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/using-with-authenticated-docs.md).

# 認証

GitBook ドキュメントに認証が必要な場合、Docs Embed がコンテンツにアクセスするには GitBook のビジタートークンが必要です。

方法は 2 つあります:

1. **トークンを直接渡す** （推奨）- GitBook のビジタートークンを使って埋め込みを初期化します。
2. **Cookie ベースで検出する** - 読み込み前に GitBook のビジタートークンを確認します。

## 方法 1: トークンを直接渡す（推奨）

埋め込みを初期化するときに、GitBook のビジタートークンを次のように渡します `visitor.token`.

`visitor.token` これは、ID プロバイダーの生のアクセストークンや ID トークンではありません。これは、認証済みドキュメントへのアクセス用に GitBook が発行するビジタートークンです。その `your-jwt-token` これらの例の値は、その GitBook 発行のトークンを表します。

{% tabs %}
{% tab title="スタンドアロンスクリプト" %}

```html
<script src="https://docs.company.com/~gitbook/embed/script.js?jwt_token=your-jwt-token"></script>
<script>
  window.GitBook(
    "init",
    { siteURL: "https://docs.company.com" },
    { visitor: { token: "your-jwt-token" } }
  );
  window.GitBook("show");
</script>
```

{% endtab %}

{% tab title="NPMパッケージ" %}

```javascript
import { createGitBook } from "@gitbook/embed";

const gitbook = createGitBook({
  siteURL: "https://docs.company.com",
});

const iframe = document.createElement("iframe");
iframe.src = gitbook.getFrameURL({
  visitor: {
    token: "your-jwt-token",
    unsignedClaims: { userId: "123", plan: "premium" },
  },
});
```

{% endtab %}

{% tab title="Reactコンポーネント" %}

```jsx
<GitBookProvider siteURL="https://docs.company.com">
  <GitBookFrame
    visitor={{
      token: "your-jwt-token",
      unsignedClaims: { userId: "123" },
    }}
  />
</GitBookProvider>
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Embed の設定 API は変更されていません。GitBook 発行のビジタートークンを次のように渡します `visitor.token`.

認証済みサイトでは、GitBook はこのトークンをサイトに次のように渡します `jwt_token` iframe/script の URL に。認証済みサイトからスタンドアロンのスクリプトを読み込む場合は、次を含める必要があります `jwt_token` の `<script src>` URL。
{% endhint %}

## OIDC ベースのサイト

Docs Embed は HS256 を使用する GitBook のビジタートークンフローを受け入れます。このアルゴリズムを変更して、RS256 の ID プロバイダートークンを受け入れるようにすることはできません。

OIDC プロバイダーのアクセストークンや ID トークンを次のように渡さないでください `visitor.token`。RS256 を使用する Auth0 や Descope のトークンは互換性がなく、署名アルゴリズムのため Docs Embed はそれらを拒否します。ID プロバイダートークンをそのまま通したり、再署名したり、そこから GitBook のビジタートークンを発行したりしないでください。

OIDC ベースのドキュメントサイトでは、次のフローを使用します:

1. ユーザーを保護されたドキュメントサイトの URL に送ります。たとえば次のようにします `https://docs.example.com`.
2. ドキュメントサイトで通常の対話型 OIDC サインインを完了します。
3. GitBook がドキュメントサイトのセッションを確立し、保存した後 `gitbook-visitor-token`、そのトークンを取得します。
4. このページでは、Cookie ベースまたは直接トークンの方法でそのトークンを渡します。

このフローには、事前にドキュメントサイトへのサインインが成功している必要があります。また、必要な Cookie とドメインが利用可能である必要があります。

{% hint style="warning" %}
Docs Embed は、ドキュメントサイトの OIDC 認可ハンドシェイクを開始したり、途中でリダイレクトしたり、サイレントに完了したりできません。初めての認証済み訪問者が埋め込み内だけで完全にアクセスする必要がある場合、サポートされている統合方法はありません。認証済み埋め込みを読み込む前に、明示的なドキュメントサイトのサインイン手順を踏ませてください。
{% endhint %}

## 方法 2: Cookie ベースの検出

ドキュメントサイトがビジタートークンを Cookie に保存している場合（次のように `gitbook-visitor-token`）、埋め込みの読み込み前にそれを確認できます。

ユーザーが認証済みドキュメントサイトにサインインすると、GitBook はブラウザーの Cookie に次のキーでビジタートークンを保存します `gitbook-visitor-token`。埋め込みがドキュメントからコンテンツを取得するには、このトークンが必要です。

**フローは次のとおりです:**

1. ユーザーがドキュメントサイトにサインインします。
2. GitBook がビジタートークンをブラウザー Cookie に保存します。
3. アプリがトークンを確認します。
4. トークンが存在する場合は、埋め込みを読み込み、トークンを渡します。
5. トークンが存在しない場合は、ユーザーをドキュメントサイトに送ってサインインさせます。

{% tabs %}
{% tab title="スタンドアロンスクリプト" %}
**コピペ用スニペット**

このスニペットは、ユーザーがドキュメントサイトへのサインインを完了した後にのみ使用してください:

```html
<script>
  (function () {
    // Cookie 内のビジタートークンを確認する
    function getCookie(name) {
      var value = "; " + document.cookie;
      var parts = value.split("; " + name + "=");
      if (parts.length === 2) return parts.pop().split(";").shift();
    }

    var token = getCookie("gitbook-visitor-token");

    if (!token) {
      console.warn("[Docs Embed] 埋め込みを読み込む前に https://docs.example.com でサインインしてください。");
      return;
    }

    // トークンがあるので、埋め込みを読み込む
    var script = document.createElement("script");
    script.src =
      "https://docs.example.com/~gitbook/embed/script.js?jwt_token=" +
      encodeURIComponent(token);
    script.async = true;
    script.onload = function () {
      window.GitBook(
        "init",
        { siteURL: "https://docs.example.com" },
        { visitor: { token: token } }
      );
      window.GitBook("show");
    };
    document.head.appendChild(script);
  })();
</script>
```

{% hint style="warning" %}
置き換える `docs.example.com` 実際のドキュメントサイトの URL に置き換えてください。
{% endhint %}

**代替案: ユーザーにサインインを促す**

トークンがない場合は、ユーザーを保護されたドキュメントサイトの URL に送ります。これで、サポートされている対話型 OIDC サインインフローが開始されます:

```html
<script>
  (function () {
    function getCookie(name) {
      var value = "; " + document.cookie;
      var parts = value.split("; " + name + "=");
      if (parts.length === 2) return parts.pop().split(";").shift();
    }

    var token = getCookie("gitbook-visitor-token");

    if (!token) {
      // ドキュメントにリダイレクトするか、メッセージを表示する
      alert("ヘルプにアクセスするには、ドキュメントにサインインしてください。");
      window.location.href = "https://docs.example.com";
      return;
    }

    // トークン付きで埋め込みを読み込む
    var script = document.createElement("script");
    script.src =
      "https://docs.example.com/~gitbook/embed/script.js?jwt_token=" +
      encodeURIComponent(token);
    script.async = true;
    script.onload = function () {
      window.GitBook(
        "init",
        { siteURL: "https://docs.example.com" },
        { visitor: { token: token } }
      );
      window.GitBook("show");
    };
    document.head.appendChild(script);
  })();
</script>
```

{% endtab %}

{% tab title="NPMパッケージ" %}
NPM パッケージを使用する場合は、初期化前にトークンを確認してください:

```javascript
import { createGitBook } from "@gitbook/embed";

function initializeEmbed() {
  // Cookie 内のトークンを確認する
  const getCookie = (name) => {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(";").shift();
  };

  const token = getCookie("gitbook-visitor-token");

  if (!token) {
    console.warn("[Docs Embed] 埋め込みを読み込む前にドキュメントサイトにサインインしてください。");
    return null;
  }

  const gitbook = createGitBook({
    siteURL: "https://docs.example.com",
  });

  const iframe = document.createElement("iframe");
  iframe.src = gitbook.getFrameURL({
    visitor: { token: token },
  });
  const frame = gitbook.createFrame(iframe);

  document.getElementById("embed-container").appendChild(iframe);
  return frame;
}

initializeEmbed();
```

{% endtab %}

{% tab title="Reactコンポーネント" %}
React アプリでは、ドキュメントサイトへのサインインでビジタートークンが作成された後に、埋め込みを条件付きでレンダリングします:

```jsx
import { useEffect, useState } from "react";
import { GitBookProvider, GitBookFrame } from "@gitbook/embed/react";

function App() {
  const [token, setToken] = useState(null);

  useEffect(() => {
    // Cookie 内のトークンを確認する
    const getCookie = (name) => {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop().split(";").shift();
    };

    const visitorToken = getCookie("gitbook-visitor-token");
    setToken(visitorToken);
  }, []);

  if (!token) {
    return (
      <div>
        <p>ヘルプにアクセスするにはサインインしてください。</p>
        <a href="https://docs.example.com">サインイン</a>
      </div>
    );
  }

  return (
    <GitBookProvider siteURL="https://docs.example.com">
      <YourAppContent />
      <GitBookFrame visitor={{ token: token }} />
    </GitBookProvider>
  );
}
```

{% endtab %}
{% endtabs %}

## よくある落とし穴

* **ID プロバイダートークンを使用する** – OIDC のアクセストークンや ID トークンを次のように使用しないでください: `visitor.token`。ドキュメントサイトでの認証後は、GitBook が発行した HS256 ビジタートークンを使用してください。
* **サインイン前に埋め込みを読み込む** – 初回訪問者には、スクリプトやコンポーネントを読み込む前にドキュメントサイトでサインインを完了してもらってください。
* **ドメイン間でトークンが保持されない** – ブラウザーのセキュリティポリシーにより、Cookie は異なるドメイン間では保持されません。アプリとドキュメントは同一ドメインまたはサブドメイン上にある必要があり、そうでなければトークンを直接渡してください。
* **トークンの有効期限切れ** – トークンは期限切れになることがあります。埋め込みで認証エラーが返る場合は、ユーザーに再度サインインを促してください。
* **間違った Cookie 名を使用している** – トークンは次の名前で保存されます: `gitbook-visitor-token`、ではなく `gitbook-token` またはその派生名です。
* **init/getFrameURL にトークンを渡していない** – Cookie ベースの方法を使う場合は、必ずトークンを次に渡してください: `GitBook('init', ..., { visitor: { token } })` または `getFrameURL({ visitor: { token } })`.

## デバッグ

トークンが存在することを確認するには、ブラウザーのコンソールを開いて次を実行します:

```javascript
document.cookie.split(";").find((c) => c.includes("gitbook-visitor-token"));
```

これが返す値が `undefined`、ユーザーはまだドキュメントにサインインしていません。

## 次のステップ

* [埋め込みのカスタマイズ](/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/configuration/customizing-docs-embed.md) – ウェルカムメッセージとアクションを追加する
* [カスタムツールの作成](/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/configuration/creating-custom-tools.md) – 製品 API と連携する
* [Docs Embed のドキュメント](/docs/documentation/ja-gitbook-documentation/gong-kai/embedding.md) – 埋め込みガイドの完全版


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://gitbook.com/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/using-with-authenticated-docs.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
