> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PlayFab API 用の Microsoft Entra ID 認証

> PKCE、デバイス コード、暗黙的付与などの OAuth 2.0 フローを使用し、Microsoft Entra ID の委任トークンで PlayFab の Admin、Server、entity API に認証します。

PlayFab では、Admin、Server、entity API を呼び出すための Microsoft Entra ID (以前は Azure Active Directory) 認証をサポートしています。Entra ID 認証を使用すると、開発者のシークレット キーの代わりに Microsoft ID でサインインし、委任アクセス トークンを使用します。アプリケーションは、authorization code with PKCE、device code、implicit grant などの標準の OAuth 2.0 パブリック クライアント フローを使用してサインイン エクスペリエンスを処理します。

<Note>
  Entra ID 認証は、Admin、Server、および一部の entity API 呼び出しのための開発者シークレット キーの代替手段です。プレイヤー向けの Client と entity API では、引き続きプレイヤー サインインで取得したセッション チケットと entity トークンを使用します。Entra ID で利用できるのは、*title* entity トークンで呼び出し可能な entity API のみです。シークレット キーの詳細については、[Secret key management](/services/playfab/live-service-management/gamemanager/secret-key-management) を参照してください。
</Note>

## Entra ID 認証を使用する理由

開発者シークレット キーはシンプルで使いやすいですが、Entra ID 認証にはいくつかの利点があります。

* **共有シークレットなし** — パブリック クライアント フローではクライアント シークレットは不要です。トークンは短命で、サインインしたユーザーに限定されます。
* **個別の説明責任** — 各 API 呼び出しが特定のユーザー ID に紐付けられ、誰が何をしたかを容易に監査できます。
* **条件付きアクセス** — 組織は IP 制限、多要素認証 (MFA)、デバイス コンプライアンス チェックなどの Entra ID ポリシーを適用できます。

## Entra ID 認証の仕組み

Microsoft Entra ID を扱ったことがない方のために説明すると、これは Microsoft のクラウド ID サービスであり、Microsoft 365、XBOX 開発者アカウント、Azure を支えている ID システムと同じものです。PlayFab がスタジオに長期間有効なシークレット キーを発行する代わりに、ツールが Entra ID に開発者のサインインを依頼し、短命の **アクセス トークン** を返してもらいます。PlayFab は、スタジオのメンバーであるユーザー向けに Entra ID が発行するトークンを信頼します。

3 つの当事者が関わります。

* **開発者。** Microsoft アカウント (個人) または職場/学校アカウント (Entra ID) でサインインしているあなたです。
* **Entra ID のアプリ登録。** PlayFab を呼び出すツール - CLI、ビルド スクリプト、社内ダッシュボードなど - を表します。「このアプリはサインイン ユーザーに代わって PlayFab のアクセス トークンを要求できます」と Entra ID に伝えます。
* **PlayFab サービス。** PlayFab はアプリケーション ID `448adbda-b8d8-4f33-a1b0-ac58cf44d4c1` の下で Entra ID に登録されており、`plugin` という委任アクセス許可を公開します。コードがスコープ `448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin` を要求すると、Entra ID は PlayFab が受け入れるトークンを発行します。

典型的な呼び出しは次のようになります。

1. コードは Microsoft Authentication Library (MSAL) を使用してサインインを開始します。通常はブラウザーのポップアップまたはデバイス コード プロンプトです。
2. ユーザーは Microsoft ID でサインインし、アプリが自分の代わりに PlayFab を呼び出すことに同意します。
3. MSAL はアクセス トークン (JWT) を返し、リフレッシュ トークンをキャッシュするため、以後の呼び出しではプロンプトをスキップできます。
4. コードは各 PlayFab リクエストに `Authorization: Bearer <token>` ヘッダーとしてトークンを送信します。
5. PlayFab はトークンを検証し、一致するスタジオ ユーザーにマッピングし、そのユーザーのロールに基づいて呼び出しを認可します。

この記事全体で使用される Entra ID の用語の定義については、末尾の [用語集](#glossary) を参照してください。

## 前提条件

* Entra ID がバックエンドの Microsoft アカウント (職場または学校アカウント) または個人の Microsoft アカウント (MSA)。
* PlayFab タイトル。詳細については、[PlayFab アカウントを作成する](/services/playfab/identity/dev-identity/pfab-account) を参照してください。
* Microsoft Entra ID テナントでアプリケーションを登録する権限。
* 呼び出し側のユーザーは PlayFab スタジオに追加され、タイトル管理者として割り当てられている必要があります。ロールの詳細については、[PlayFab ユーザー ロール](/services/playfab/identity/dev-identity/permissions/playfab-user-roles) を参照してください。

## Entra ID にパブリック クライアント アプリケーションを登録する

サインインしたユーザーに代わってコードが委任トークンを要求できるように、Entra ID テナントにアプリケーションを登録する必要があります。パブリック クライアント フロー (SPA、デバイス コード、暗黙的) では、クライアント シークレットは必要ありません。

1. [Azure Portal](https://portal.azure.com) にサインインします。

2. **App registrations** を検索して選択し、**New registration** を選択します。

3. アプリケーションの名前を入力します (例: `PlayFab API Client`)。

4. **Supported account types** で、組織の要件に一致するオプションを選択します。最大の柔軟性を得るには、**Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts** を選択します。このオプションは、任意の Microsoft アカウントによる認証を許可します。

5. アプリケーションのタイプに基づいて **Redirect URI** を構成します。
   * シングル ページ アプリケーション (SPA) の場合、**Single-page application (SPA)** を選択し、リダイレクト URI を入力します (たとえば、`http://localhost:3000`)。
   * デバイス コード フローを使用するネイティブまたはコンソール アプリケーションの場合、**Public client/native (mobile & desktop)** を選択し、`http://localhost` を入力します。

6. **Register** を選択します。概要ページで、**Application (client) ID** をメモします。この値はトークンを要求する際に必要になります。

7. アプリ登録に PlayFab API アクセス許可を追加します。
   1. Azure Portal でアプリ登録に移動し、**API permissions** を選択します。
   2. **Add a permission** > **APIs my organization uses** を選択します。
   3. PlayFab アプリケーション ID `448adbda-b8d8-4f33-a1b0-ac58cf44d4c1` を検索して選択します。
   4. **Delegated permissions** を選択し、**plugin** アクセス許可をオンにして、**Add permissions** を選択します。

<Note>
  シナリオで機密 (Web アプリ) クライアントが必要な場合は、**Certificates & secrets** の下でクライアント シークレットも作成する必要があります。この記事はシークレットを必要としないパブリック クライアント フローに焦点を当てています。機密クライアント フローの詳細については、[Microsoft ID プラットフォームと OAuth 2.0 認可コード フロー](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow) を参照してください。
</Note>

## PlayFab スタジオ アクセスをセットアップする

PlayFab は、スタジオ メンバーシップに対して Entra ID トークンを検証します。呼び出し元のユーザーは PlayFab スタジオに追加され、適切なロールを付与されている必要があります。

1. スタジオ管理者に [Game Manager](https://developer.playfab.com) にサインインしてもらいます。

2. スタジオの **Users** セクションに移動します。

3. **Add User** を選択し、API アクセスが必要な開発者の Microsoft アカウントのメール アドレスを入力します。

4. 認証プロバイダーとして **Microsoft** を選択します。

5. Admin または Server API アクセスを含むロールをユーザーに割り当てます。少なくとも、API を呼び出す必要があるタイトルの **title admin** である必要があります。

6. **Add user** を選択して招待を送信します。

ユーザーの追加とロールの割り当ての詳細については、[PlayFab Game Manager のアカウント認証](/services/playfab/identity/dev-identity/authentication/aad-authentication) を参照してください。

## アクセス トークンを取得する

アプリケーションは、ユーザーをサインインし、Entra ID から委任アクセス トークンを取得する責任を負います。以下の例は、一般的なパブリック クライアント フローを示しています。

### 対話型ブラウザー フロー (デスクトップおよびコンソール アプリに推奨)

対話型ブラウザー フローは、サインインのためにシステム ブラウザー ウィンドウを開きます。デスクトップ アプリケーションとローカル開発ツールに推奨されるオプションです。

```csharp theme={null}
using Microsoft.Identity.Client;

// Build an MSAL public client app. The client ID identifies your Entra app
// registration; "common" lets users sign in from any Entra tenant or with a
// personal Microsoft account.
var app = PublicClientApplicationBuilder.Create("your-client-id")
    .WithAuthority("https://login.microsoftonline.com/common")
    .WithDefaultRedirectUri()
    .Build();

// The scope identifies the PlayFab API and the delegated permission ("plugin")
// your app is requesting on behalf of the signed-in user.
string[] scopes = ["448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin"];

AuthenticationResult result;
try
{
    // Try to get a token from MSAL's cache without prompting the user.
    // This succeeds on subsequent runs while the cached refresh token is valid.
    var accounts = await app.GetAccountsAsync();
    result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
        .ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    // No cached token, or it expired and can't be refreshed silently.
    // Open the system browser so the user can sign in interactively.
    result = await app.AcquireTokenInteractive(scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();
}

// The access token is what you send to PlayFab in the Authorization header.
string accessToken = result.AccessToken;
```

### PKCE を伴う認可コード (SPA に推奨)

Proof Key for Code Exchange (PKCE) を伴う認可コード フローは、シングル ページ アプリケーションに推奨されるアプローチです。次の JavaScript の例では、Microsoft Authentication Library (MSAL) を使用します。

```javascript theme={null}
import { PublicClientApplication } from "@azure/msal-browser";

// MSAL config. clientId is your Entra app registration's Application (client) ID.
// "common" lets users sign in from any tenant or with a personal account.
// redirectUri must match a Single-page application redirect URI on the app registration.
const msalConfig = {
    auth: {
        clientId: "your-client-id",
        authority: "https://login.microsoftonline.com/common",
        redirectUri: "http://localhost:3000"
    }
};

const msalInstance = new PublicClientApplication(msalConfig);
await msalInstance.initialize();

// loginPopup runs the auth code + PKCE flow in a pop-up window. The scope
// asks Entra ID for a delegated token that PlayFab will accept.
const loginResponse = await msalInstance.loginPopup({
    scopes: ["448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin"]
});

// Send this token to PlayFab in the Authorization header.
const accessToken = loginResponse.accessToken;
```

## アクセス トークンで PlayFab API を呼び出す

`X-SecretKey` ヘッダーを使用する代わりに、PlayFab API リクエストの `Authorization` ヘッダーに Bearer トークンとして Entra ID アクセス トークンを含めます。

### リクエスト例

```http theme={null}
POST https://{titleId}.playfabapi.com/Server/GetPlayerProfile
Content-Type: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi...

{
    "PlayFabId": "ABCDEF1234567890"
}
```

<Note>
  同じリクエストで `X-SecretKey` と `Authorization: Bearer` の両方を使用することはできません。呼び出しごとに 1 つの認証方法を使用してください。
</Note>

### C# の例

以下の例では、Microsoft Authentication Library (MSAL) を使用してトークンを取得し、`Server/GetTime` API を呼び出します。`your-client-id` をアプリ登録の **Application (client) ID** に置き換えてください。

```csharp theme={null}
using Microsoft.Identity.Client;
using System.Net.Http.Headers;
using System.Text;

// PlayFab API endpoint. Every title gets its own subdomain on playfabapi.com.
string titleId = "YOUR_TITLE_ID";
string host = $"{titleId}.playfabapi.com";
string url = $"https://{host}/Server/GetTime";

// MSAL configuration.
// clientId   - your Entra app registration's Application (client) ID.
// authority  - "common" lets any Entra tenant or personal Microsoft account sign in.
// scopes     - the PlayFab application ID + the "plugin" delegated permission.
string clientId = "your-client-id";
string authority = "https://login.microsoftonline.com/common";
string[] scopes = ["448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin"];

// Build the MSAL public client. Public clients (desktop, CLI, mobile) don't use
// a client secret; tokens are bound to the signed-in user instead.
var app = PublicClientApplicationBuilder.Create(clientId)
    .WithAuthority(authority)
    .WithDefaultRedirectUri()
    .Build();

AuthenticationResult authResult;
try
{
    // Reuse a cached token if MSAL has one. Avoids prompting on every run.
    var accounts = await app.GetAccountsAsync();
    authResult = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
        .ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    // First run, or the cached token expired. Open the system browser to sign in.
    authResult = await app.AcquireTokenInteractive(scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();
}

// Call PlayFab. Replace X-SecretKey with an Authorization: Bearer header
// containing the Entra ID access token.
using var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
request.Content = new StringContent("{}", Encoding.UTF8, "application/json");

var response = await httpClient.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();

Console.WriteLine($"Status: {response.StatusCode}");
Console.WriteLine($"Response: {body}");
```

### Node.js の例

以下の例では、`@azure/msal-node` ライブラリを使用してトークンを取得し、`Server/GetTime` API を呼び出します。`your-client-id` をアプリ登録の **Application (client) ID** に置き換えてください。

```javascript theme={null}
import { PublicClientApplication } from "@azure/msal-node";
import open from "open";

// PlayFab API endpoint for your title.
const titleId = "YOUR_TITLE_ID";
const host = `${titleId}.playfabapi.com`;
const url = `https://${host}/Server/GetTime`;

// MSAL configuration.
// clientId  - your Entra app registration's Application (client) ID.
// authority - "common" accepts any Entra tenant or personal Microsoft account.
const msalConfig = {
    auth: {
        clientId: "your-client-id",
        authority: "https://login.microsoftonline.com/common",
    },
};

const pca = new PublicClientApplication(msalConfig);

// Token request:
// scopes      - PlayFab application ID + the "plugin" delegated permission.
// redirectUri - must match a Public client redirect URI on the app registration.
// openBrowser - MSAL calls this to launch the user's default browser for sign-in.
const tokenRequest = {
    scopes: ["448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin"],
    redirectUri: "http://localhost:3000",
    openBrowser: async (url) => { await open(url); },
    successTemplate: "<h1>Authentication complete. You can close this window.</h1>",
};

// Sign the user in and obtain a delegated access token.
const authResult = await pca.acquireTokenInteractive(tokenRequest);

// Call PlayFab with the token in the Authorization header instead of X-SecretKey.
const response = await fetch(url, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authResult.accessToken}`,
    },
    body: JSON.stringify({}),
});

const body = await response.json();
console.log(`Status: ${response.status}`);
console.log("Response:", JSON.stringify(body, null, 2));
```

## トークンのリフレッシュ

Entra ID アクセス トークンは短命 (通常 60〜90 分) です。MSAL を使用している場合、各リクエストの前に `AcquireTokenSilent` (C#) を呼び出すか、トークン キャッシュを確認してください。キャッシュされたリフレッシュ トークンが利用可能な場合、MSAL は自動的にリフレッシュを処理します。

手動でトークンを管理している場合は、現在のトークンが期限切れになる前に同じサインイン フローを使用して新しいトークンを要求してください。

<Info>
  使用中にトークンが期限切れになった場合、PlayFab は `401 Unauthorized` の応答を返します。アプリケーションは、このエラーを処理して新しいトークンを要求し、呼び出しを再試行する必要があります。
</Info>

## トラブルシューティング

| 問題                                             | 原因                                    | 解決方法                                        |
| ---------------------------------------------- | ------------------------------------- | ------------------------------------------- |
| `401 Unauthorized`                             | トークンの期限切れまたは無効                        | 再度サインインして新しいトークンを要求します                      |
| `403 Forbidden`                                | ユーザーがタイトルに必要なロールを持っていない               | Game Manager でスタジオ メンバーシップとタイトル管理者ロールを確認します |
| `AADSTS50076: Need multifactor authentication` | 条件付きアクセス ポリシーが MFA を要求しています           | MFA チャレンジを完了して再試行します                        |
| `AADSTS700016: Application not found`          | クライアント ID が正しくないか、アプリが想定されるテナントにありません | クライアント ID とテナント ID を確認します                   |

### エラー応答の例

Bearer トークンが不足、不正、または期限切れの場合の PlayFab からの `401 Unauthorized` は次のようになります。

```json theme={null}
{
    "code": 401,
    "status": "Unauthorized",
    "error": "NotAuthenticated",
    "errorCode": 1074,
    "errorMessage": "Invalid \"Authorization\" header."
}
```

サインインしたユーザーが認証されているものの、タイトルの管理者アクセス許可を持っていない場合の PlayFab からの `403 Forbidden` は次のようになります。

```json theme={null}
{
    "code": 403,
    "status": "Forbidden",
    "error": "NotAuthorizedByTitle",
    "errorCode": 1191,
    "errorMessage": "Developer does not have admin permission for this title."
}
```

## 制限事項

現在、PlayFab SDK は Entra ID 認証をサポートしていません。現時点で Entra ID トークンで PlayFab API を呼び出すには、[C#](#c-example) および [Node.js](#nodejs-example) の例に示すように、直接 HTTP 呼び出しを使用し、自分で `Authorization: Bearer <token>` ヘッダーを設定してください。SDK のサポートは今後のリリースで予定されています。

## 用語集

| 用語               | 意味                                                                                                                                                        |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **テナント**         | Entra ID における分離されたディレクトリ。会社には 1 つのテナントがあり、個人の Microsoft アカウントは *consumers* という共有テナントを使用します。サンプルで使用される `common` オーソリティを使うと、任意のテナントからサインインできます。             |
| **アプリ登録**        | クライアント アプリケーション (クライアント ID、許可されたリダイレクト URI、要求された API アクセス許可) を記述する Entra ID のレコード。                                                                        |
| **委任アクセス許可**     | アプリが独自の権限で動作するのではなく、サインインしたユーザー *に代わって* 受け取るアクセス許可。                                                                                                       |
| **パブリック クライアント** | シークレットを安全に保存できないクライアント - デスクトップやモバイル アプリ、CLI、シングル ページ Web アプリなど。パブリック クライアントは、クライアント シークレットの代わりに authorization code with PKCE や device code などのフローを使用します。 |
| **スコープ**         | コードが Entra ID に要求している API アクセス許可。PlayFab の場合、スコープは `448adbda-b8d8-4f33-a1b0-ac58cf44d4c1/plugin` です。                                                      |
| **MSAL**         | Microsoft Authentication Library。手作業で OAuth リクエストを構築する必要がないように、これらすべてのフローを実装する公式クライアント ライブラリです。                                                           |

## 関連項目

* [シークレット キーの管理](/services/playfab/live-service-management/gamemanager/secret-key-management)
* [PlayFab Game Manager のアカウント認証](/services/playfab/identity/dev-identity/authentication/aad-authentication)
* [PlayFab ユーザー ロール](/services/playfab/identity/dev-identity/permissions/playfab-user-roles)
* [API アクセス ポリシー](/services/playfab/api-references/api-access-policy)
* [Microsoft Entra ID のドキュメント](https://learn.microsoft.com/en-us/entra/fundamentals/whatis)


## Related topics

- [PlayFab 用の Microsoft アカウント認証](/ja-jp/services/playfab/identity/dev-identity/authentication/aad-authentication.md)
- [Grafana を Insights に接続する](/ja-jp/services/playfab/data-analytics/legacy/connectivity/connecting-grafana-to-insights.md)
- [PlayFab Insights 用の Microsoft Entra ID アプリを作成する](/ja-jp/services/playfab/data-analytics/legacy/connectivity/creating-AAD-app-for-insights.md)
- [サービス間認証用のユーザー Store ID を要求する](/ja-jp/publishing/xstore-commerce/xstore-requesting-userstoreid.md)
- [Microsoft Store API を使用してサービスを認証する](/ja-jp/publishing/xstore-commerce/xstore-authenticating-service.md)
