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

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

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

> [accordion] AI を使って Auth0 を統合する
>
> 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/docs/ja-jp/quickstart/agent-skills)

> [!NOTE]
>
> **前提条件:** 始める前に、以下がインストールされていることを確認してください。
>
> * **[.NET SDK](https://dotnet.microsoft.com/download)** 8.0 以降
> * お好みのコードエディター (Visual Studio、VS Code、または Rider)
> * Auth0 アカウント ([無料でサインアップ](https://auth0.com/signup))

## はじめに

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

**1. 新しいプロジェクトを作成**

このQuickstart向けに新しいBlazor Serverプロジェクトを作成する

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

プロジェクトを開く

```shellscript theme={null}
cd SampleBlazorApp
```

**2. Auth0 SDKをインストールする**

```shellscript theme={null}
dotnet add package Auth0.AspNetCore.Authentication
```

**3. Auth0 アプリケーションを設定する**

次に、Auth0 テナントで新しいアプリケーションを作成し、プロジェクトに設定を追加します。

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

> [tab] CLI
>
> プロジェクトのルートディレクトリで次のシェルコマンドを実行し、Auth0 アプリケーションを作成して `appsettings.json` を更新します。
>
> ```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"
> ```
>
> > [!NOTE]
> >
> > このコマンドは以下を実行します：
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. `http://localhost:5000` 用に構成されたAuth0 Regular Web Applicationを作成します
> > 3. `appsettings.json` を `Auth0:Domain`、`Auth0:ClientId`、`Auth0:ClientSecret` で更新します

> [tab] 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** の値に置き換えます

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

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

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

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

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

**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();
```

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

**5. LoginページとLogoutページを追加**

ユーザーが認証できるように、Login ページと Logout ページを作成します。

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

> [tab] 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] 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
> ```

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

**6. プロファイルページの作成とレイアウトの更新**

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

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

> [tab] Mac/Linux
>
> ```shellscript theme={null}
> touch Components/Pages/Profile.razor
> ```

> [tab] Windows (PowerShell)
>
> ```powershell theme={null}
> New-Item -ItemType File -Force -Path Components/Pages/Profile.razor
> ```

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

**7. アプリケーションを起動する**

```shellscript theme={null}
dotnet run
```

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

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

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

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

***

## 高度な使い方

> [accordion] 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] 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] 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] 構成を取得できない
>
> **問題:** `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] 構成値が見つからない
>
> **問題:** `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] ミドルウェアの順序の問題
>
> **問題:** 構成が正しいにもかかわらず、認証が機能しない。
>
> **解決策:** ミドルウェアが正しい順序で配置されていることを確認してください。`UseAuthentication()` は `UseAuthorization()` より前に記述する必要があります。
>
> ```csharp Program.cs theme={null}
> app.UseRouting();
> app.UseAuthentication();  // UseAuthorization より前に記述する必要があります
> app.UseAuthorization();
> app.MapControllerRoute(...);
> ```

***

## 追加リソース

> [card] [GitHub リポジトリ](https://github.com/auth0/auth0-aspnetcore-authentication)
>
> ソースコードと Issue トラッカー

> [card] [API リファレンス](https://auth0.github.io/auth0-aspnetcore-authentication/)
>
> 詳細な API ドキュメント

> [card] [コミュニティフォーラム](https://community.auth0.com/)
>
> Auth0 コミュニティからサポートを受ける

***

## サンプルアプリケーション

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

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

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

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

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

***
