> 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/publish/site-audience/authenticated-access/setting-up-a-custom-backend.md). Agents can also search and read this documentation through its [MCP server](https://gitbook.com/docs/~gitbook/mcp).

# 独自のログインページをホスティングする

ドキュメント閲覧者向けにカスタムログイン画面を設定します

独自の認証サービスを使って、ドキュメントサイトへの訪問者をサインインさせます。次の2つの構成で利用できます。

* **サイト全体を非公開にする。** まず、サイトのオーディエンスを認証済みアクセスに設定します。詳しくは、 [認証済みアクセスを有効にする](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/enabling-authenticated-access.md).
* **サイトは公開し、サインインした訪問者には追加コンテンツを表示する。** オーディエンスは公開のまま、アダプティブコンテンツを有効にします。詳しい手順については、 [How to mix public and private content](https://gitbook.com/docs/guides/docs-personalization-and-authentication/how-to-show-private-content-to-signed-in-visitors-on-a-public-docs-site.md).

{% hint style="info" %}
サポート対象の認証プロバイダーを使用している場合、または [OpenID Connect](https://auth0.com/docs/authenticate/protocols/openid-connect-protocol) （OIDC）準拠のバックエンドを使用している場合は、より簡単に設定できる連携ガイドをご覧ください。\
\
[Auth0](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-auth0.md) | [Azure AD](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-azure-ad.md) | [Okta](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-okta.md) | [AWS Cognito](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-aws-cognito.md) | [OIDC](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-oidc.md)
{% endhint %}

### サインインの仕組み

非公開サイトでは、サインインしていない訪問者は全員、GitBookによってログインページにリダイレクトされます。公開サイトでは、訪問者はサインインリンクから開始します。

1. GitBookは訪問者をログインURLにリダイレクトし、訪問者が最初にアクセスしたページを示す `location` クエリパラメーターを追加します。
2. ログインページで訪問者をサインインさせます。
3. バックエンドで、サイトの秘密鍵を使って署名したJSON Web Token（JWT）を作成します。コンテンツを出し分ける場合、トークンには訪問者のクレームを含めます。
4. バックエンドで、訪問者をドキュメントサイトの `location` ページにリダイレクトします。その際、トークンを `jwt_token` クエリパラメーターまたはCookieに含めます。

### 概要

GitBookサイトにカスタム認証システムを設定するには、次の主要な手順に従ってください。

{% stepper %}
{% step %}
[**ユーザーを認証するためのカスタムバックエンドを作成する**](#id-1.-create-a-custom-backend-to-authenticate-your-users)

ユーザーにログインを促し、認証するバックエンドを実装します。
{% endstep %}

{% step %}
[**JWT トークンに署名して GitBook に渡す**](#id-2.-sign-and-pass-a-jwt-token-to-gitbook)

JWT トークンを作成し、サイトの秘密鍵で署名します。
{% endstep %}

{% step %}
[**ログイン URL を設定する**](#id-3.-configure-a-login-url)

認証されていない訪問者がサイトにアクセスしたときに使用されるURLを設定します。
{% endstep %}

{% step %}
[**マルチテナントの認証済みアクセスを設定する（任意）**](#id-4.-set-up-multi-tenant-authenticated-access-optional)

複数の GitBook サイトにわたる認証を処理するよう、バックエンドを設定します。
{% endstep %}

{% step %}
[**アダプティブコンテンツ用にバックエンドを設定する（任意）**](#id-5.-configure-your-backend-for-adaptive-content-optional)

GitBook のアダプティブコンテンツで動作するようにバックエンドを設定します。
{% endstep %}
{% endstepper %}

### 1. ユーザーを認証するためのカスタムバックエンドを作成する

訪問者をサインインさせるには、ログインと認証を処理できるサーバーが必要です。

バックエンドは次のことを行う必要があります。

* 希望する認証方法を使ってユーザーにログインを促す。
* ユーザーの資格情報を検証し、認証する。
* 認証が成功したら、 **JSON Web Token（JWT）** を生成して署名します。
* URLにJWTを含めるか、cookieに保存して、ユーザーをGitBookにリダイレクトします。

### 2. JWT トークンに署名して GitBook に渡す

バックエンドでユーザーを認証したら、JWTを **生成し** 、 **GitBookに渡す** 必要があります。 **ユーザーをサイトにリダイレクトする** 際に渡してください。トークンには、 **秘密鍵** を使って署名します。秘密鍵は、サイトのオーディエンス設定に表示されています。詳しくは、 [ログインURLを設定する](#id-3.-configure-a-login-url).

{% hint style="info" %}
サイトが [カスタムドメイン](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/custom-domain.md)で配信されている場合、署名付きJWTはリダイレクトURLに追加する代わりに、 `gitbook-visitor-token` を自分のドメインのCookieに保存できます。詳しくは [署名付きCookie](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/adaptive-content/enabling-adaptive-content/cookies.md#signed-cookie).
{% endhint %}

次の例では、カスタムバックエンド内のログイン要求ハンドラーがどのようなものになり得るかを示します。

{% code title="index.ts" %}

```typescript
import { Request, Response } from 'express';
import * as jose from 'jose';

import { getUserInfo } from '../services/user-info-service';
import { getFeatureFlags } from '../services/feature-flags-service';

const GITBOOK_VISITOR_SIGNING_KEY = process.env.GITBOOK_VISITOR_SIGNING_KEY!;
const GITBOOK_DOCS_URL = 'https://mycompany.gitbook.io/myspace';

export async function handleAppLoginRequest(req: Request, res: Response) {
    // ログインリクエストを処理するためのビジネスロジック
    // たとえば、資格情報を確認してユーザーを認証する
    //
    // 例:
    // const loggedInUser = await authenticateUser(req.body.username, req.body.password);
    
    // 署名付き JWT を生成する
    const gitbookVisitorJWT = await new jose.SignJWT({})
        .setProtectedHeader({ alg: 'HS256' })
        .setIssuedAt()
        .setExpirationTime('2h') // 任意の2時間の有効期限
        .sign(new TextEncoder().encode(GITBOOK_VISITOR_SIGNING_KEY));
    
    // URL に JWT トークンを含めてユーザーを GitBook にリダイレクトする
    const redirectURL = `${GITBOOK_DOCS_URL}/?jwt_token=${gitbookVisitorJWT}`;
    res.redirect(redirectURL);
}
```

{% endcode %}

#### GitBook セッションから訪問者をログアウトさせる

GitBook セッションから訪問者をサインアウトさせるには、サイトの URL に `~gitbook/auth/logout` を追加してリダイレクトします。

`https://mycompany.gitbook.io/myspace/~gitbook/auth/logout`

このエンドポイントは、訪問者を GitBook からのみサインアウトさせます。独自の ID プロバイダーからもサインアウトさせたい場合は、ログアウトフロー内で別途処理してください。

### 3. ログイン URL を設定する

GitBookは訪問者をログインURLにリダイレクトしてサインインさせます。非公開サイトでは、訪問者がサインインしていない場合にリダイレクトされます。また、どのサイトでも、訪問者がサインインリンクを使うとリダイレクトされます。

このURLは、カスタムバックエンド内のハンドラーを指している必要があります。そこでログインを促し、認証を行い、その後JWTをURLに含めてサイトへリダイレクトできます。

たとえば、ログイン画面の URL が `https://example.com/login`の場合、この URL をログイン URL として指定してください。

ログインURLを設定するには、次の手順に従います。

1. ドキュメントサイトで、 **［設定］→［オーディエンス］**.
2. ［ **認証を設定**］で、 **認証バックエンド** を **カスタム**.
3. に設定します。 **秘密鍵**をコピーします。バックエンドでトークンに署名する際に使用します。
4. ［ **ログインURL**］に、ログイン処理を行うURLを入力します。
5. 任意：［ **ログアウトURL**］に、サインアウト後に訪問者に表示するページを入力します。
6. を選択します。 **保存**.

**認証を設定** は、サイトのオーディエンスが認証済みアクセスに設定されている場合、またはアダプティブコンテンツが有効になっている場合に表示されます。

<figure><img src="https://4217681718-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNkEGS7hzeqa35sMXQZ4X%2Fuploads%2Fgit-blob-4de2aada8e403a5af7f9b5dfed7a0af109338204%2F25_04_10_setting_up_a_custom_backend.png?alt=media" alt="A GitBook screenshot showing where to configure a login URL"><figcaption><p>ログイン URL を設定する</p></figcaption></figure>

#### GitBook のログインエンドポイントを使用する

公開サイトにサインイン用リンクを設置する場合は、次の URL にリンクしてください。 `<publishedSiteURL>/~gitbook/auth/login`.

このエンドポイントは、訪問者をサイトに設定された認証バックエンドへリダイレクトします。また、訪問者が元いたページに対応する `location` クエリパラメーターも追加します。

これは、ヘッダーリンクや、サインイン後に同じページへ戻したいその他の प्रवेश点に便利です。

ログイン URL にリダイレクトする際、GitBook はログイン URL に `location` クエリパラメーターを追加します。このパラメーターをハンドラーで利用して、ユーザーを元の場所にリダイレクトできます。

```javascript
const gitbookVisitorJWT = await new jose.SignJWT({})
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('2h') // 任意の2時間の有効期限
    .sign(new TextEncoder().encode(GITBOOK_VISITOR_SIGNING_KEY));
    
// 元の GitBook ドキュメント URL に、jwt_token クエリパラメータとして JWT を含めてリダイレクトする
// 場所が指定されている場合、ユーザーは元の目的地に戻される
const redirectURL = `${GITBOOK_DOCS_URL}/${req.query.location || ''}?jwt_token=${gitbookVisitorJWT}`;
res.redirect(redirectURL);
```

{% hint style="warning" %}
GitBookは `location` 検索パラメーターを使用するため、ログインURLでは使用できません。たとえば、 `https://auth.gitbook.com/?location=something` は有効なログインURLではありません。
{% endhint %}

#### MCP 認可リクエストをリダイレクトする

訪問者が公開ドキュメントの [MCP サーバー](https://gitbook.com/docs/documentation/ja-gitbook-documentation/ai-for-your-readers/mcp-servers-for-published-docs.md) に接続すると、GitBook はその訪問者を認証バックエンドにリダイレクトします。リダイレクトには、 `location` MCP 認可エンドポイントへのパスを指定するパラメーターで、次の値を持つ `gb_oauth_state` 値を含みます。例：

```
~gitbook/oauth2/v1/<site-id>/authorize?gb_oauth_state=<consent_state>
```

バックエンドは、このパスを使って GitBook サイトへ戻る最終的なリダイレクト先を組み立てる必要があります。

GitBook はサイトの設定に応じて、次の2つのエンドポイントのいずれかからこのフローを開始します。

* `~gitbook/mcp/auth` 適応型コンテンツが有効になっている、部分的に認証されたサイトの場合に使用します。
* `~gitbook/mcp` 認証済みアクセスを使用するサイトの場合に使用します。

バックエンドで訪問者を認証したら、次の値を追加してリダイレクト先 URL を作成します。 `location` パスを GitBook サイトのベース URL に追加します。 `gb_oauth_state` クエリパラメーターはそのままにし、さらに次の値を追加します。 `jwt_token=<token>` バックエンドで生成した署名済み JWT を含むパラメーターです。

バックエンドが訪問者をリダイレクトする最終的な URL は、次のようになります。

```
https://<publishedSiteURL>/~gitbook/oauth2/v1/<site-id>/authorize?gb_oauth_state=<consent_state>&jwt_token=<token>
```

#### GitBook のログアウトエンドポイントを使用する

公開サイトにサインアウト用リンクを設置する場合は、次の URL にリンクします。 `<publishedSiteURL>/~gitbook/auth/logout`.

にリンクしてください。このエンドポイントは、訪問者を GitBook セッションからサインアウトさせます。

### 4. マルチテナントの認証済みアクセスを設定する（任意）

GitBook を複数の顧客向けにコンテンツを提供するプラットフォームとして使用している場合、マルチテナントの認証済みアクセスを設定する必要があるでしょう。認証バックエンドは、複数の異なるサイトにわたる認証を処理する責任を負う必要があります。これは、カスタム認証バックエンドのコードにいくつか小さな変更を加えるだけで GitBook で実現できます。

#### 認証サーバーにすべてのテナントを追加する

認証バックエンドは、JWT 署名キーと、処理対象の GitBook サイトすべての URL を把握している必要があります。たとえば、組織内に Customer A と Customer B の2つのサイトがある場合、認証コードで次のような対応表を保存していると考えられます。

```typescript
const CUSTOMER_A = {
  jwtSigningKey: 'aaa-aaa-aaa-aaa',
  url: 'https://mycompany.gitbook.io/customer-a'
};

const CUSTOMER_B = {
  jwtSigningKey: 'bbb-bbb-bbb-bbb',
  url: 'https://mycompany.gitbook.io/customer-b'
};
```

#### 認証サーバーに追加のコンテキストを与える

GitBook がユーザーのリクエストを認証できない場合、ログイン URL にリダイレクトします。この URL は認証バックエンドを指し、そこでユーザーを認証して要求されたコンテンツへ戻す責任があります。

複数のテナントをサポートするには、認証バックエンドがユーザーがどの GitBook サイトにアクセスすべきかを把握している必要があります。この情報はログイン URL で渡せます。

たとえば、各サイトのログインURLは次のように設定できます。

その後、認証バックエンドはこの情報を確認し、それに応じて正しいサイトへのリダイレクトを処理できます。

```javascript
const customerInfo = req.query.site === 'customer-a' ? CUSTOMER_A : CUSTOMER_B;
  
const gitbookVisitorJWT = await new jose.SignJWT({})
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('2h') // 任意の2時間の有効期限
    .sign(new TextEncoder().encode(customerInfo.jwtSigningKey));
    
// 元の GitBook ドキュメント URL に、jwt_token クエリパラメータとして JWT を含めてリダイレクトする
// 場所が指定されている場合、ユーザーは元の目的地に戻される
const redirectURL = `${customerInfo.url}/${req.query.location || ''}?jwt_token=${gitbookVisitorJWT}`;
res.redirect(redirectURL);
```

### 5. アダプティブコンテンツ用にバックエンドを設定する（任意）

認証済みアクセスの設定でAdaptive Content機能を活用するには、ユーザーをサイトへリダイレクトする際にカスタムバックエンドが生成し、URLに含めるJWTのペイロードに、追加のユーザー属性（クレーム）を含めることができます。

JWT に含めると、これらのクレームは GitBook によって使用され、 [コンテンツを動的に適応させます](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/adaptive-content/adapting-your-content.md) 対象はサイトの訪問者です。

まとめると、次のコード例は、JWT にこれらのクレームを含める方法を示しており、その結果 GitBook は訪問者向けにコンテンツを適応させることができます。

{% code title="index.ts" %}

```typescript
import { Request, Response } from 'express';
import * as jose from 'jose';

import { getUserInfo } from '../services/user-info-service';
import { getFeatureFlags } from '../services/feature-flags-service';

const GITBOOK_VISITOR_SIGNING_KEY = process.env.GITBOOK_VISITOR_SIGNING_KEY!;
const GITBOOK_DOCS_URL = 'https://mycompany.gitbook.io/myspace';

export async function handleAppLoginRequest(req: Request, res: Response) {
    // ログインリクエストを処理するためのビジネスロジック
    // たとえば、資格情報を確認してユーザーを認証する
    //
    // 例:
    // const loggedInUser = await authenticateUser(req.body.username, req.body.password);
    
    // この例では、ログイン済みユーザーオブジェクトがあると仮定する
    const loggedInUser = { id: '12345' }; // 実際の認証ロジックに置き換える

    // GitBook に渡すユーザー情報を取得する
    const userInfo = await getUserInfo(loggedInUser.id);
    
    // 署名付き JWT を生成し、ユーザー属性をクレームとして含める
    const gitbookVisitorClaims = {
        firstName: userInfo.firstName,
        lastName: userInfo.lastName,
        isBetaUser: userInfo.isBetaUser,
        products: userInfo.products.map((product) => product.name),
        featureFlags: await getFeatureFlags({ userId: loggedInUser.id })
    };
    
    const gitbookVisitorJWT = await new jose.SignJWT(gitbookVisitorClaims)
        .setProtectedHeader({ alg: 'HS256' })
        .setIssuedAt()
        .setExpirationTime('2h') // 任意の2時間の有効期限
        .sign(new TextEncoder().encode(GITBOOK_VISITOR_SIGNING_KEY));
    
    // URL に JWT トークンを含めてユーザーを GitBook にリダイレクトする
    const redirectURL = `${GITBOOK_DOCS_URL}/?jwt_token=${gitbookVisitorJWT}`;
    res.redirect(redirectURL);
}
```

{% endcode %}

GitBook に送信する適切なクレームを設定して構成したら、「[コンテンツを調整する](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/adaptive-content/adapting-your-content.md)」に移動して、サイトの設定を続けます。公開サイトの設定手順については、 [How to mix public and private content](https://gitbook.com/docs/guides/docs-personalization-and-authentication/how-to-show-private-content-to-signed-in-visitors-on-a-public-docs-site.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/ja-gitbook-documentation/publish/site-audience/authenticated-access/setting-up-a-custom-backend.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.
