> 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/zh/publish/embedding/using-with-authenticated-docs.md).

# 身份验证

通过传递访客令牌或使用已认证访问，将 Docs Embed 用于需要身份验证的站点

如果您的 GitBook 文档需要身份验证，Docs Embed 需要 GitBook 访客令牌才能访问内容。

有两种方式：

1. **直接传递令牌** （推荐）- 使用 GitBook 访客令牌初始化嵌入。
2. **使用基于 Cookie 的检测** - 在加载前检查 GitBook 访客令牌。

## 方式 1：直接传递令牌（推荐）

初始化嵌入时，将 GitBook 访客令牌作为 `visitor.token`.

`visitor.token` 它不是来自身份提供方的原始访问令牌或 ID 令牌，而是 GitBook 为经过身份验证的文档访问签发的 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` URL 中包含 `<script src>` 。
{% endhint %}

## 基于 OIDC 的网站

Docs Embed 使用 HS256 接受 GitBook 访客令牌流程。您无法更改或配置此算法来接受 RS256 身份提供方令牌。

请勿将 OIDC 提供方的访问令牌或 ID 令牌作为 `visitor.token`传递。使用 RS256 的 Auth0 和 Descope 令牌不兼容，Docs Embed 会因其签名算法而拒绝这些令牌。请勿转发、重新签名或根据身份提供方令牌签发 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 () {
    // Check for the visitor token in cookies
    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] Sign in at https://docs.example.com before loading the embed.");
      return;
    }

    // Token exists, load the embed
    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) {
      // Redirect to docs or show a message
      alert("Please sign in to your docs to access help.");
      window.location.href = "https://docs.example.com";
      return;
    }

    // Load the embed with token
    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() {
  // Check for token in cookies
  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] Sign in to the docs site before loading the 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(() => {
    // Check for token in cookies
    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 %}

## 常见问题

* **使用身份提供方令牌** – 不要将 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`，则用户尚未登录文档站点。

## 下一步

* [自定义嵌入内容](https://gitbook.com/docs/documentation/zh/publish/embedding/configuration/customizing-docs-embed.md) – 添加欢迎消息和操作
* [创建自定义工具](https://gitbook.com/docs/documentation/zh/publish/embedding/configuration/creating-custom-tools.md) – 与产品 API 集成
* [文档嵌入指南](https://gitbook.com/docs/documentation/zh/publish/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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/zh/publish/embedding/using-with-authenticated-docs.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
