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

> このガイドでは、Auth0.AspNetCore.Authentication SDK を使用して、新規または既存の Blazor Server アプリケーションに Auth0 を統合する方法を説明します。

# Blazor Server アプリケーションにログインを追加する

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

<HowToSchema />

<Accordion title="AI を使って Auth0 を統合する" icon="microchip-ai" iconType="solid" defaultOpen>
  Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使えば、[agent skills](https://agentskills.io/home) を利用して、数分で Auth0 認証を自動追加できます。

  **インストール:**

  ```bash theme={null}
  npx skills add auth0/agent-skills --skill auth0
  ```

  **続いて、AI アシスタントに次のように依頼します。**

  ```text theme={null}
  Add Auth0 authentication to my Blazor Server app
  ```

  AI アシスタントが、Auth0 アプリケーションの作成、資格情報の取得、Auth0 ASP.NET Core Authentication SDK のインストール、認証ミドルウェアの構成、ログイン/ログアウト フローの実装を自動で行います。[agent skills の完全なドキュメント →](/docs/ja-jp/quickstart/agent-skills)
</Accordion>

<Note>
  **前提条件:** 始める前に、以下がインストールされていることを確認してください。

  * **[.NET SDK](https://dotnet.microsoft.com/download)** 8.0 以降
  * お好みのコードエディター (Visual Studio、VS Code、または Rider)
  * Auth0 アカウント ([無料でサインアップ](https://auth0.com/signup))
</Note>

<div id="get-started">
  ## はじめに
</div>

Auth0 を使用すると、認証をすばやく追加し、アプリケーションからユーザープロファイル情報にアクセスできるようになります。このガイドでは、`Auth0.AspNetCore.Authentication` SDK を使用して、Auth0 を新規または既存の Blazor Server アプリケーションに統合する方法を説明します。

<Steps>
  <Step title="新しいプロジェクトを作成" stepNumber={1}>
    このQuickstart向けに新しいBlazor Serverプロジェクトを作成する

    ```shellscript theme={null}
    dotnet new blazor -n SampleBlazorApp --interactivity Server
    ```

    プロジェクトを開く

    ```shellscript theme={null}
    cd SampleBlazorApp
    ```
  </Step>

  <Step title="Auth0 SDKをインストールする" stepNumber={2}>
    ```shellscript theme={null}
    dotnet add package Auth0.AspNetCore.Authentication
    ```
  </Step>

  <Step title="Auth0 アプリケーションを設定する" stepNumber={3}>
    次に、Auth0 テナントで新しいアプリケーションを作成し、プロジェクトに設定を追加します。

    CLIコマンドを実行してAuth0 アプリケーションを自動的に設定する方法と、Auth0 Dashboardから手動で行う方法のいずれかを選択できます。

    <Tabs>
      <Tab title="CLI">
        プロジェクトのルートディレクトリで次のシェルコマンドを実行し、Auth0 アプリケーションを作成して `appsettings.json` を更新します。

        <CodeGroup>
          ```shellscript Mac theme={null}
          # Auth0 CLIをインストールする（未インストールの場合）
          brew tap auth0/auth0-cli && brew install auth0

          # Auth0 アプリケーションを設定し、appsettings.jsonを生成する
          auth0 qs setup --app --type regular --framework aspnet-blazor --port 5000 --name "My Blazor Server App"
          ```

          ```powershell Windows theme={null}
          # Auth0 CLIをインストールする（未インストールの場合）
          scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
          scoop install auth0

          # Auth0 アプリケーションを設定し、appsettings.jsonを生成する
          auth0 qs setup --app --type regular --framework aspnet-blazor --port 5000 --name "My Blazor Server App"
          ```
        </CodeGroup>

        <Note>
          このコマンドは以下を実行します：

          1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
          2. `http://localhost:5000` 用に構成されたAuth0 Regular Web Applicationを作成します
          3. `appsettings.json` を `Auth0:Domain`、`Auth0:ClientId`、`Auth0:ClientSecret` で更新します
        </Note>
      </Tab>

      <Tab title="Auth0 Dashboard">
        始める前に、プロジェクトのルートディレクトリにある `appsettings.json` を作成または更新してください

        ```json appsettings.json theme={null}
        {
          "Logging": {
            "LogLevel": {
              "Default": "Information",
              "Microsoft.AspNetCore": "Warning"
            }
          },
          "AllowedHosts": "*",
          "Auth0": {
            "Domain": "YOUR_AUTH0_DOMAIN",
            "ClientId": "YOUR_CLIENT_ID",
            "ClientSecret": "YOUR_CLIENT_SECRET"
          }
        }
        ```

        1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/)を開きます
        2. **Applications → Applications → Create Application** をクリックします
        3. アプリケーション名 (例: "My Blazor App") を入力します
        4. アプリケーションの種類として **Regular Web Application** を選択します
        5. **Create** をクリックします
        6. **Settings** タブを開きます
        7. `appsettings.json` ファイル内の `YOUR_AUTH0_DOMAIN`、`YOUR_CLIENT_ID`、`YOUR_CLIENT_SECRET` を、ダッシュボードの **Domain**、**Client ID**、**Client Secret** の値に置き換えます
      </Tab>
    </Tabs>

    **コールバックURLを設定する：**

    **設定**タブで、以下のURLを設定してください：

    * **許可するコールバック URL**: `http://localhost:5000/callback`
    * **許可するログアウト URL**: `http://localhost:5000`
    * **許可する Web オリジン**: `http://localhost:5000`

    **変更を保存**をクリックします

    <Info>
      **重要:** [接続を設定](https://auth0.com/docs/get-started/applications/set-up-database-connections)し、Auth0 Dashboard の **Connections** タブでお使いのアプリケーションに対してその接続を有効にしてください。
    </Info>
  </Step>

  <Step title="認証を設定する" stepNumber={4}>
    `Program.cs` を更新して、Auth0 の認証を構成します:

    ```csharp Program.cs lines theme={null}
    using Auth0.AspNetCore.Authentication;
    using SampleBlazorApp.Components;

    var builder = WebApplication.CreateBuilder(args);

    // Auth0認証を追加する
    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"];
        options.ClientId = builder.Configuration["Auth0:ClientId"];
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
    });

    // RazorコンポーネントとBlazor Serverを追加する
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();

    // カスケード認証状態を追加する
    builder.Services.AddCascadingAuthenticationState();

    // 認証エンドポイント用のRazor Pagesを追加する
    builder.Services.AddRazorPages();

    var app = builder.Build();

    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseAntiforgery();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapStaticAssets();
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();

    // 認証用のRazor Pagesをマップする
    app.MapRazorPages();

    app.Run();
    ```

    <Info>
      **注意:** ミドルウェアの順序は重要です。`UseAuthentication()` は `UseAuthorization()` より前に呼び出す必要があります。
    </Info>
  </Step>

  <Step title="LoginページとLogoutページを追加" stepNumber={5}>
    ユーザーが認証できるように、Login ページと Logout ページを作成します。

    まず、`Pages` フォルダーとファイルを作成します。

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        mkdir -p Pages && touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType Directory -Force -Path Pages; New-Item -ItemType File -Force -Path Pages/Login.cshtml, Pages/Login.cshtml.cs, Pages/Logout.cshtml, Pages/Logout.cshtml.cs, Pages/_ViewImports.razor
        ```
      </Tab>
    </Tabs>

    次に、以下のコードスニペットを追加します。

    <AuthCodeGroup>
      ```razor Pages/Login.cshtml lines theme={null}
      @page
      @model LoginModel
      ```

      ```csharp Pages/Login.cshtml.cs lines theme={null}
      using Auth0.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Mvc.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          public class LoginModel : PageModel
          {
              public async Task OnGet(string redirectUri = "/")
              {
                  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                      .WithRedirectUri(redirectUri)
                      .Build();

                  await HttpContext.ChallengeAsync(
                      Auth0Constants.AuthenticationScheme,
                      authenticationProperties);
              }
          }
      }
      ```

      ```razor Pages/Logout.cshtml lines theme={null}
      @page
      @using Microsoft.AspNetCore.Authorization
      @attribute [Authorize]
      @model LogoutModel
      ```

      ```csharp Pages/Logout.cshtml.cs lines theme={null}
      using Auth0.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication.Cookies;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          [Authorize]
          public class LogoutModel : PageModel
          {
              public async Task OnGet()
              {
                  var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                      .WithRedirectUri("/")
                      .Build();

                  await HttpContext.SignOutAsync(
                      Auth0Constants.AuthenticationScheme,
                      authenticationProperties);
                      
                  await HttpContext.SignOutAsync(
                      CookieAuthenticationDefaults.AuthenticationScheme);
              }
          }
      }
      ```

      ```razor Components/_Imports.razor lines theme={null}
      @using System.Security.Claims
      @using Microsoft.AspNetCore.Authorization
      @using Microsoft.AspNetCore.Components.Authorization
      ```

      ```razor Pages/_ViewImports.razor lines theme={null}
      @using SampleBlazorApp.Pages
      @namespace SampleBlazorApp.Pages
      @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="プロファイルページの作成とレイアウトの更新" stepNumber={6}>
    ユーザー名とclaimsを表示するカスタムのユーザープロファイルページを作成し、レイアウトを更新してLogin/Logoutリンクを追加します。

    まず、Profileコンポーネントを作成します。

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        touch Components/Pages/Profile.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType File -Force -Path Components/Pages/Profile.razor
        ```
      </Tab>
    </Tabs>

    次に、以下のコードスニペットを追加します。`MainLayout` のコードは、レイアウトの他の部分はそのままにして、先頭のセクションに追加してください。

    <AuthCodeGroup>
      ```razor Components/Pages/Profile.razor expandable lines theme={null}
      @page "/profile"
      @attribute [Authorize]

      <PageTitle>User Profile</PageTitle>

      <AuthorizeView>
          <Authorized>
              <div class="profile-container">
                  <img src="@context.User.FindFirst("picture")?.Value" 
                       alt="Profile picture" 
                       class="profile-picture" />
                  
                  <h3>Welcome, @context.User.Identity?.Name!</h3>
                  
                  <div class="profile-details">
                      <p><strong>Email:</strong> @context.User.FindFirst("email")?.Value</p>
                      <p><strong>Email Verified:</strong> @context.User.FindFirst("email_verified")?.Value</p>
                      <p><strong>Auth0 User ID:</strong> @context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value</p>
                  </div>

                  <h4>All Claims:</h4>
                  <table class="table">
                      <thead>
                          <tr>
                              <th>Claim Type</th>
                              <th>Claim Value</th>
                          </tr>
                      </thead>
                      <tbody>
                          @foreach (var claim in context.User.Claims)
                          {
                              <tr>
                                  <td>@claim.Type</td>
                                  <td>@claim.Value</td>
                              </tr>
                          }
                      </tbody>
                  </table>
              </div>
          </Authorized>
          <NotAuthorized>
              <p>You must be logged in to view this page.</p>
              <a href="/Login?redirectUri=/profile">Log in</a>
          </NotAuthorized>
      </AuthorizeView>
      ```

      ```razor Components/Layout/MainLayout.razor lines theme={null}
      <div class="top-row px-4">
          <AuthorizeView>
              <NotAuthorized>
                  <a href="/Login">Log in</a>
              </NotAuthorized>
              <Authorized>
                  <span>Hello, @context.User.Identity?.Name!</span>
                  <a href="/Profile">Profile</a>
                  <a href="/Logout">Log out</a>
              </Authorized>
          </AuthorizeView>
      </div>
      ```

      ```razor Components/Routes.razor lines theme={null}
      <CascadingAuthenticationState>
          <Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
              <Found Context="routeData">
                  <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
                  <FocusOnNavigate RouteData="routeData" Selector="h1" />
              </Found>
          </Router>
      </CascadingAuthenticationState>
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="アプリケーションを起動する" stepNumber={7}>
    ```shellscript theme={null}
    dotnet run
    ```

    アプリケーションが起動し、待ち受け中のURLが表示されるはずです：

    ```
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:5000
    ```

    ブラウザーを開いて `http://localhost:5000` にアクセスします。ナビゲーションの **Login** リンクをクリックします。Auth0 のログインページにリダイレクトされます。
    ログインすると、アプリケーションにリダイレクトされ、ナビゲーションに自分の名前が表示されます。
  </Step>
</Steps>

<Check>
  **チェックポイント**

  これで、Auth0 で保護された完全に機能する Blazor Server アプリケーションが [http://localhost:5000](http://localhost:5000) で動作しているはずです。ユーザーはログインし、プロファイルを表示し、ログアウトできます。
</Check>

***

<div id="advanced-usage">
  ## 高度な使い方
</div>

<Accordion title="Login パラメーターをカスタマイズする">
  Auth0 のログインページにカスタムパラメーターを渡せます。

  ```csharp Pages/Login.cshtml.cs theme={null}
  public async Task OnGet(string redirectUri = "/")
  {
      var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
          .WithRedirectUri(redirectUri)
          .WithParameter("screen_hint", "signup")  // サインアップページを表示
          .WithParameter("ui_locales", "es")       // 言語をスペイン語に設定
          .Build();

      await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
  }
  ```
</Accordion>

<Accordion title="API 呼び出し用にトークンを保存する">
  ユーザーに代わって外部 API を呼び出す必要がある場合は、トークンを取得して保存できます。

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
  })
  .WithAccessToken(options =>
  {
      options.Audience = "https://your-api.example.com";
      options.UseRefreshTokens = true;
  });
  ```

  次に、アクセストークンを取得します。

  ```csharp theme={null}
  var accessToken = await HttpContext.GetTokenAsync("access_token");

  // アクセストークンを使って API を呼び出す
  var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization = 
      new AuthenticationHeaderValue("Bearer", accessToken);

  var response = await client.GetAsync("https://your-api.example.com/data");
  var data = await response.Content.ReadAsStringAsync();
  ```
</Accordion>

<Accordion title="Organizations を設定する">
  B2B シナリオ向けに organization のサポートを設定します。

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
      options.Organization = builder.Configuration["Auth0:Organization"];
  });
  ```

  または、ログイン時に organization を指定します。

  ```csharp Pages/Login.cshtml.cs theme={null}
  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
      .WithOrganization("org_abc123")
      .WithRedirectUri("/")
      .Build();
  ```
</Accordion>

***

<div id="common-issues">
  ## よくある問題
</div>

<AccordionGroup>
  <Accordion title="構成を取得できない">
    **問題:** `Unable to obtain configuration from: https://your-tenant.auth0.com/.well-known/openid-configuration`

    **解決策:** Domain が正しく、`https://` を含んでいないことを確認してください。authority はライブラリによって自動的に構築されます。

    ```json theme={null}
    {
      "Auth0": {
        "Domain": "your-tenant.auth0.com"  // 正しい - プロトコルなし
      }
    }
    ```

    あわせて、次の点も確認してください。

    * Domain 値の末尾にスラッシュが付いていない
    * アプリケーションから Auth0 にアクセスできるインターネット接続がある
    * Domain 形式がテナントのリージョンと一致している (`.auth0.com`, `.us.auth0.com`, `.eu.auth0.com`)
  </Accordion>

  <Accordion title="構成値が見つからない">
    **問題:** `ArgumentNullException: Value cannot be null. (Parameter 'Domain')` または同様のエラー。

    **解決策:** `appsettings.json` に Domain、ClientId、ClientSecret を含む Auth0 セクションがあることを確認してください。また、構成が正しく読み込まれていることも確認してください。

    ```csharp Program.cs theme={null}
    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"]
            ?? throw new InvalidOperationException("Auth0:Domain is required");
        options.ClientId = builder.Configuration["Auth0:ClientId"]
            ?? throw new InvalidOperationException("Auth0:ClientId is required");
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"]
            ?? throw new InvalidOperationException("Auth0:ClientSecret is required");
    });
    ```
  </Accordion>

  <Accordion title="ミドルウェアの順序の問題">
    **問題:** 構成が正しいにもかかわらず、認証が機能しない。

    **解決策:** ミドルウェアが正しい順序で配置されていることを確認してください。`UseAuthentication()` は `UseAuthorization()` より前に記述する必要があります。

    ```csharp Program.cs theme={null}
    app.UseRouting();
    app.UseAuthentication();  // UseAuthorization より前に記述する必要があります
    app.UseAuthorization();
    app.MapControllerRoute(...);
    ```
  </Accordion>
</AccordionGroup>

***

<div id="additional-resources">
  ## 追加リソース
</div>

<CardGroup cols={2}>
  <Card title="GitHub リポジトリ" icon="github" href="https://github.com/auth0/auth0-aspnetcore-authentication">
    ソースコードと Issue トラッカー
  </Card>

  <Card title="API リファレンス" icon="code" href="https://auth0.github.io/auth0-aspnetcore-authentication/">
    詳細な API ドキュメント
  </Card>

  <Card title="コミュニティフォーラム" icon="comments" href="https://community.auth0.com/">
    Auth0 コミュニティからサポートを受ける
  </Card>
</CardGroup>

***

<div id="sample-application">
  ## サンプルアプリケーション
</div>

以下に、Auth0 と ASP.NET Core MVC の連携を示すサンプルアプリケーションがあります。

<Card title="ASP.NET Core Blazor アプリ" icon="github" href="https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample">
  ログイン、ログアウト、ユーザープロファイルなどの例が含まれています。
</Card>

クローンして実行します:

```bash theme={null}
git clone https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample

# appsettings.jsonをAuth0の設定で更新する
dotnet run
```

***
