{"meta":{"title":"GitHub OAuth のセットアップ","intro":"ユーザーが自分のGitHub アカウントで認証を行い、アプリケーションでCopilotを使用できるようにします。 これにより、個々のアカウント、組織のメンバーシップ、およびエンタープライズ ID がサポートされます。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/how-tos","title":"方法"},{"href":"/ja/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/ja/copilot/how-tos/copilot-sdk/setup","title":"Copilot SDK を設定する"},{"href":"/ja/copilot/how-tos/copilot-sdk/setup/github-oauth","title":"GitHub OAuth"}],"documentType":"article"},"body":"# GitHub OAuth のセットアップ\n\nユーザーが自分のGitHub アカウントで認証を行い、アプリケーションでCopilotを使用できるようにします。 これにより、個々のアカウント、組織のメンバーシップ、およびエンタープライズ ID がサポートされます。\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n**ベスト for:** マルチユーザー アプリ、組織アクセス制御を備えた内部ツール、SaaS 製品、ユーザーがGitHubアカウントを持つアプリ。\n\n## どのように機能するのか\n\nGitHub OAuth アプリ (または GitHub アプリ) を作成し、ユーザーがそれを承認し、アクセス トークンを SDK に渡します。 Copilot要求は、Copilot サブスクリプションを使用して、認証された各ユーザーに代わって行われます。\n\n![図: 説明されたプロセスを示すシーケンス図。](/assets/images/help/copilot/copilot-sdk/setup-github-oauth-diagram-0.png)\n\n**主な特性:**\n\n* 各ユーザーは、独自のGitHub アカウントで認証します\n* Copilot使用量は各ユーザーのサブスクリプションに課金されます\n* GitHub の組織アカウントとエンタープライズ アカウントをサポート\n* アプリがモデル API キーを処理することはありません。GitHubはすべてを管理します\n\n## Architecture\n\n![図: 説明されたプロセスを示すフローチャート。](/assets/images/help/copilot/copilot-sdk/setup-github-oauth-diagram-1.png)\n\n## 手順 1: GitHub OAuth アプリを作成する\n\n1. \\[**GitHub Settings → Developer Settings → OAuth Apps → New OAuth App** (または組織の場合: **開発者設定→開発者向け設定**) に移動します。\n\n2. 次の項目を入力します。\n   * **アプリケーション名**: アプリの名前\n   * **ホーム ページ URL**: アプリの URL\n   * **承認コールバック URL**: OAuth コールバック エンドポイント (例: `https://yourapp.com/auth/callback`)\n\n3. **クライアント ID を**メモし、**クライアント シークレット**を生成する\n\n> **GitHub アプリと OAuth アプリ:** 両方とも機能します。 GitHub Apps では、よりきめ細かいアクセス許可が提供され、新しいプロジェクトに推奨されます。 OAuth アプリの設定は簡単です。 トークン フローは、SDK の観点から見ると同じです。\n\n## 手順 2: OAuth フローを実装する\n\nアプリケーションが標準の GitHub OAuth フローを処理します。 サーバー側のトークン交換を次に示します。\n\n```typescript\n// Server-side: Exchange authorization code for user token\nasync function handleOAuthCallback(code: string): Promise<string> {\n    const response = await fetch(\"https://github.com/login/oauth/access_token\", {\n        method: \"POST\",\n        headers: {\n            \"Content-Type\": \"application/json\",\n            Accept: \"application/json\",\n        },\n        body: JSON.stringify({\n            client_id: process.env.GITHUB_CLIENT_ID,\n            client_secret: process.env.GITHUB_CLIENT_SECRET,\n            code,\n        }),\n    });\n\n    const data = await response.json();\n    return data.access_token; // gho_xxxx or ghu_xxxx\n}\n```\n\n## 手順 3: トークンを SDK に渡す\n\n認証されたユーザーごとに SDK クライアントを作成し、トークンを渡します。\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\n// Create a client for an authenticated user\nfunction createClientForUser(userToken: string): CopilotClient {\n    return new CopilotClient({\n        gitHubToken: userToken,\n        useLoggedInUser: false,  // Don't fall back to CLI login\n    });\n}\n\n// Usage\nconst client = createClientForUser(\"gho_user_access_token\");\nconst session = await client.createSession({\n    sessionId: `user-${userId}-session`,\n    model: \"gpt-5.4\",\n});\n\nconst response = await session.sendAndWait({ prompt: \"Hello!\" });\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nfrom copilot import CopilotClient\nfrom copilot.session import PermissionHandler\n\ndef create_client_for_user(user_token: str) -> CopilotClient:\n    return CopilotClient({\n        \"github_token\": user_token,\n        \"use_logged_in_user\": False,\n    })\n\n# Usage\nclient = create_client_for_user(\"gho_user_access_token\")\nawait client.start()\n\nsession = await client.create_session(on_permission_request=PermissionHandler.approve_all, model=\"gpt-5.4\", session_id=f\"user-{user_id}-session\")\n\nresponse = await session.send_and_wait(\"Hello!\")\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nfunc createClientForUser(userToken string) *copilot.Client {\n    return copilot.NewClient(&copilot.ClientOptions{\n        GitHubToken:     userToken,\n        UseLoggedInUser: copilot.Bool(false),\n    })\n}\n\n// Usage\nclient := createClientForUser(\"gho_user_access_token\")\nclient.Start(ctx)\ndefer client.Stop()\n\nsession, _ := client.CreateSession(ctx, &copilot.SessionConfig{\n    SessionID: fmt.Sprintf(\"user-%s-session\", userID),\n    Model:     \"gpt-5.4\",\n})\nresponse, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: \"Hello!\"})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nCopilotClient CreateClientForUser(string userToken) =>\n    new CopilotClient(new CopilotClientOptions\n    {\n        GitHubToken = userToken,\n        UseLoggedInUser = false,\n    });\n\n// Usage\nawait using var client = CreateClientForUser(\"gho_user_access_token\");\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    SessionId = $\"user-{userId}-session\",\n    Model = \"gpt-5.4\",\n});\n\nvar response = await session.SendAndWaitAsync(\n    new MessageOptions { Prompt = \"Hello!\" });\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nimport com.github.copilot.CopilotClient;\nimport com.github.copilot.rpc.*;\n\nCopilotClient createClientForUser(String userToken) throws Exception {\n    var client = new CopilotClient(new CopilotClientOptions()\n        .setGitHubToken(userToken)\n        .setUseLoggedInUser(false)\n    );\n    client.start().get();\n    return client;\n}\n\n// Usage — use try-with-resources to ensure cleanup\nvar userId = \"user1\";\ntry (var client = createClientForUser(\"gho_user_access_token\")) {\n    var session = client.createSession(new SessionConfig()\n        .setSessionId(String.format(\"user-%s-session\", userId))\n        .setModel(\"gpt-5.4\")\n        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n    ).get();\n\n    var response = session.sendAndWait(new MessageOptions()\n        .setPrompt(\"Hello!\")).get();\n}\n```\n\n</div>\n\n</div>\n\n## エンタープライズおよび組織のアクセス\n\nGitHub OAuth は、エンタープライズ シナリオを自然にサポートします。 ユーザーがGitHubで認証を行うと、組織のメンバーシップと企業の関連付けが行われます。\n\n![図: 説明されたプロセスを示すフローチャート。](/assets/images/help/copilot/copilot-sdk/setup-github-oauth-diagram-2.png)\n\n### 組織のメンバーシップを確認する\n\nOAuth の後、ユーザーが組織に属していることを確認します。\n\n```typescript\nasync function verifyOrgMembership(\n    token: string,\n    requiredOrg: string\n): Promise<boolean> {\n    const response = await fetch(\"https://api.github.com/user/orgs\", {\n        headers: { Authorization: `Bearer ${token}` },\n    });\n    const orgs = await response.json();\n    return orgs.some((org: any) => org.login === requiredOrg);\n}\n\n// In your auth flow\nconst token = await handleOAuthCallback(code);\nif (!await verifyOrgMembership(token, \"my-company\")) {\n    throw new Error(\"User is not a member of the required organization\");\n}\nconst client = createClientForUser(token);\n```\n\n### エンタープライズ マネージド ユーザー (EMU)\n\nGitHub Enterprise Managed Users、フローは同じです。EMU ユーザーは、他のユーザーと同様GitHub OAuth を介して認証します。 エンタープライズ ポリシー (IP 制限、SAML SSO) は、GitHubによって自動的に適用されます。\n\n```typescript\n// No special SDK configuration needed for EMU\n// Enterprise policies are enforced server-side by GitHub\nconst client = new CopilotClient({\n    gitHubToken: emuUserToken,  // Works the same as regular tokens\n    useLoggedInUser: false,\n});\n```\n\n## サポートされているトークンの種類\n\n| トークン プレフィックス  | 情報源                        | 動作しますか？ |\n| ------------- | -------------------------- | ------- |\n| `gho_`        | OAuth ユーザー アクセス トークン       | ✅       |\n| `ghu_`        | GitHub App のユーザー アクセス トークン | ✅       |\n| `github_pat_` | きめ細かい個人用アクセス トークン          | ✅       |\n| `ghp_`        | 従来の個人用アクセス トークン            |         |\n| ❌ (非推奨)       |                            |         |\n\n## トークンのライフサイクル\n\n![図: 説明されたプロセスを示すフローチャート。](/assets/images/help/copilot/copilot-sdk/setup-github-oauth-diagram-3.png)\n\n**大事な：** アプリケーションは、トークンのストレージ、更新、および有効期限の処理を担当します。 SDK では、指定したトークンが使用されます。OAuth ライフサイクルは管理されません。\n\n### トークン更新パターン\n\n```typescript\nasync function getOrRefreshToken(userId: string): Promise<string> {\n    const stored = await tokenStore.get(userId);\n\n    if (stored && !isExpired(stored)) {\n        return stored.accessToken;\n    }\n\n    if (stored?.refreshToken) {\n        const refreshed = await refreshGitHubToken(stored.refreshToken);\n        await tokenStore.set(userId, refreshed);\n        return refreshed.accessToken;\n    }\n\n    throw new Error(\"User must re-authenticate\");\n}\n```\n\n## マルチユーザー パターン\n\n### ユーザーごとに 1 つのクライアント (推奨)\n\n各ユーザーは、独自のトークンを使用して独自の SDK クライアントを取得します。 これにより、最も強力な分離が提供されます。\n\n```typescript\nconst clients = new Map<string, CopilotClient>();\n\nfunction getClientForUser(userId: string, token: string): CopilotClient {\n    if (!clients.has(userId)) {\n        clients.set(userId, new CopilotClient({\n            gitHubToken: token,\n            useLoggedInUser: false,\n        }));\n    }\n    return clients.get(userId)!;\n}\n```\n\n### 要求ごとのトークンを使用した共有 CLI\n\nリソース占有領域を軽くするために、1 つの外部 CLI サーバーを実行し、セッションごとにトークンを渡すことができます。 このパターンについては [、AUTOTITLE](/ja/copilot/how-tos/copilot-sdk/setup/backend-services) を参照してください。\n\n## 制限事項\n\n| 制限事項                       | 詳細情報                                |\n| -------------------------- | ----------------------------------- |\n| **Copilot サブスクリプションが必要です** | 各ユーザーにはアクティブなCopilot サブスクリプションが必要です |\n| **トークン管理はユーザーの責任です**       | 保存、更新、および有効期限の処理                    |\n| **GitHub アカウントが必要です**      | ユーザーはGitHubアカウントを持っている必要があります       |\n| **ユーザーあたりのレート制限**          | 各ユーザーのCopilotレート制限に従う               |\n\n## 次に進むタイミング\n\n| 必要                                                                           | 次のガイドへ |\n| ---------------------------------------------------------------------------- | ------ |\n| GitHub アカウントを持たないユーザー                                                        |        |\n| [BYOK (独自のキーを持ち込む)](/ja/copilot/how-tos/copilot-sdk/auth/byok)               |        |\n| サーバーで SDK を実行する                                                              |        |\n| [バックエンド サービスのセットアップ](/ja/copilot/how-tos/copilot-sdk/setup/backend-services) |        |\n| 多数の同時実行ユーザーを処理する                                                             |        |\n| [スケーリングとマルチテナント](/ja/copilot/how-tos/copilot-sdk/setup/scaling)              |        |\n\n## 次のステップ\n\n* **[認証](/ja/copilot/how-tos/copilot-sdk/auth/authenticate)**: 完全な認証方法のリファレンス\n* **[バックエンド サービスのセットアップ](/ja/copilot/how-tos/copilot-sdk/setup/backend-services)**: SDK サーバー側を実行する\n* **[スケーリングとマルチテナント](/ja/copilot/how-tos/copilot-sdk/setup/scaling)**: 大規模な多数のユーザーを処理する"}