# 認証

GitBook のドキュメントに認証が必要な場合（例: OIDC、Auth0、またはカスタムバックエンドによる訪問者認証）、ユーザーの認証トークンが提供されない限り、埋め込みはドキュメントのコンテンツにアクセスできません。

アプローチは2つあります:

1. **トークンを直接渡す** （推奨）- 訪問者トークンで埋め込みを初期化する
2. **Cookie ベースの検出を使う** - 読み込み前に Cookie 内のトークンを確認する

## アプローチ1: トークンを直接渡す（推奨）

埋め込みを初期化するときに、訪問者トークンを直接渡します:

{% 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 は変更されていません。署名付き訪問者トークンは次のように渡してください `visitor.token`.

認証済みサイトでは、GitBook はこのトークンをサイトへ次のように転送します `jwt_token` iframe/script の URL 内。認証済みサイトからスタンドアロンのスクリプトを読み込む場合は、必ず `jwt_token` を `<script src>` を含める必要があります。
{% 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] 先にドキュメントへサインインしてください。");
      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 %}

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

トークンがない場合は、ユーザーにサインインを促せます:

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

## よくある落とし穴

* **サインイン前に埋め込みを読み込む** – スクリプトやコンポーネントを読み込む前に必ずトークンを確認するか、初期化時にトークンを直接渡してください。
* **トークンがドメイン間で保持されない** – ブラウザのセキュリティポリシーにより、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/docs-site/embedding/configuration/customizing-docs-embed.md) – ウェルカムメッセージとアクションを追加する
* [カスタムツールの作成](/docs/documentation/ja-gitbook-documentation/docs-site/embedding/configuration/creating-custom-tools.md) – 製品 API と統合する
* [Docs Embed のドキュメント](/docs/documentation/ja-gitbook-documentation/docs-site/embedding.md) – 埋め込みガイド کامل版


---

# Agent Instructions: 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:

```
GET https://gitbook.com/docs/documentation/ja-gitbook-documentation/docs-site/embedding/using-with-authenticated-docs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
