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

# ASP.NET MVC アプリケーションにログイン機能を追加する

> このガイドでは、Auth0.AspNetCore.Authentication SDK を使用して、新規または既存の ASP.NET MVC アプリケーションに 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 ASP.NET Core MVC 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 を使用して、新規または既存の ASP.NET MVC アプリケーションに Auth0 を統合する方法を説明します。

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

このQuickstart用の新しいASP.NET Core MVCプロジェクトを作成する

```shellscript theme={null}
dotnet new mvc -n SampleMvcApp
```

プロジェクトを開く

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

**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-mvc --port 5000 --name "My ASP.NET MVC 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-mvc --port 5000 --name "My ASP.NET MVC 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. **アプリケーション → アプリケーション → アプリケーションを作成** をクリックします
> 3. アプリケーション名を入力します (例: "My MVC 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を設定します：

* **Allowed Callback URLs**: `http://localhost:5000/callback`
* **Allowed Logout URLs**: `http://localhost:5000`
* **Allowed Web Origins**: `http://localhost:5000`

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

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

**4. 認証を設定する**

Auth0 の認証を設定するには、`Program.cs` を更新します:

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuth0WebAppAuthentication(options =>
{
    options.Domain = builder.Configuration["Auth0:Domain"];
    options.ClientId = builder.Configuration["Auth0:ClientId"];
    options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

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

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
```

**5. ログイン機能とログアウト機能を追加する**

`Controllers` フォルダーに `AccountController.cs` を作成します。

```csharp Controllers/AccountController.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;

public class AccountController : Controller
{
    public async Task Login(string returnUrl = "/")
    {
        var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
            .WithRedirectUri(returnUrl)
            .Build();

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

    [Authorize]
    public async Task Logout()
    {
        var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
            .WithRedirectUri(Url.Action("Index", "Home"))
            .Build();

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

    [Authorize]
    public IActionResult Profile()
    {
        return View();
    }
}
```

**6. Create プロファイルビュー**

新しいファイル `Views/Account/Profile.cshtml` を作成します：

```html Views/Account/Profile.cshtml lines theme={null}
@{
    ViewData["Title"] = "User Profile";
}

<div class="row">
    <div class="col-md-12">
        <h2>@ViewData["Title"]</h2>
        <div class="row">
            <div class="col-md-2">
                <img src="@User.FindFirst(c => c.Type == "picture")?.Value" alt="User's profile picture" class="img-fluid rounded-circle" />
            </div>
            <div class="col-md-10">
                <h3>@User.Identity.Name</h3>
                <p><strong>Email:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value</p>
                <p><strong>Email Verified:</strong> @User.FindFirst(c => c.Type == "email_verified")?.Value</p>
                <p><strong>User ID:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value</p>
            </div>
        </div>
        
        <h4 class="mt-4">User Claims</h4>
        <table class="table">
            <thead>
                <tr>
                    <th>Claim Type</th>
                    <th>Claim Value</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var claim in User.Claims)
                {
                    <tr>
                        <td>@claim.Type</td>
                        <td>@claim.Value</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
```

> [!NOTE]
>
> **注:** `Views/Account` ディレクトリが存在しない場合は、先に作成してください。

**7. レイアウトを更新**

Login/Logout ボタンを追加するため、レイアウト ファイルを更新します。`Views/Shared/_Layout.cshtml` で `<nav>` 要素を探し、次の内容に置き換えます：

```html Views/Shared/_Layout.cshtml lines theme={null}
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
    <div class="container-fluid">
        <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">SampleMvcApp</a>
        <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                </li>
            </ul>
            <ul class="navbar-nav">
                @if (User.Identity.IsAuthenticated)
                {
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-controller="Account" asp-action="Profile">@User.Identity.Name</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-controller="Account" asp-action="Logout">Logout</a>
                    </li>
                }
                else
                {
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-controller="Account" asp-action="Login">Login</a>
                    </li>
                }
            </ul>
        </div>
    </div>
</nav>
```

> [!NOTE]
>
> **重要:** 置き換えるのは `<nav>` 要素だけにしてください。\_Layout.cshtml のそれ以外の部分はすべてそのまま残し、特にページ コンテンツのレンダリングに必要な `@RenderBody()` 呼び出しは変更しないでください。

**8. アプリケーションを実行**

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

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

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

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

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

***

## 高度な使い方

> [accordion] ユーザープロファイル情報にアクセスする
>
> コントローラーまたはビューの `User` プロパティから、ユーザープロファイル情報にアクセスできます。
>
> ```csharp Controllers/AccountController.cs theme={null}
> [Authorize]
> public IActionResult Profile()
> {
>     var user = new
>     {
>         Name = User.Identity.Name,
>         EmailAddress = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value,
>         ProfileImage = User.FindFirst(c => c.Type == "picture")?.Value,
>         UserId = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
>     };
>
>     return View(user);
> }
> ```
>
> ユーザーのクレームには、標準的な OIDC 情報が含まれます。
>
> * **Name**: ユーザーの表示名
> * **Email**: ユーザーのメールアドレス
> * **Picture**: ユーザーのプロフィール画像 URL
> * **NameIdentifier** (sub): 一意のユーザー ID

> [accordion] Login パラメーターをカスタマイズする
>
> Auth0 Login Page にカスタムパラメーターを渡せます。
>
> ```csharp Controllers/AccountController.cs theme={null}
> public async Task Login(string returnUrl = "/")
> {
>     var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
>         .WithRedirectUri(returnUrl)
>         .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";
> });
> ```
>
> 次に、コントローラーで access token を取得します。
>
> ```csharp Controllers/ApiController.cs theme={null}
> [Authorize]
> public async Task<IActionResult> CallApi()
> {
>     var accessToken = await HttpContext.GetTokenAsync("access_token");
>
>     // 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();
>
>     return View(data);
> }
> ```

> [accordion] 認証イベントを処理する
>
> イベントを処理して、認証の動作をカスタマイズできます。
>
> ```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.Events = new Auth0WebAppWithAccessTokenEvents
>     {
>         OnMissingRefreshToken = async (context) =>
>         {
>             await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
>             var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
>                 .WithRedirectUri("/")
>                 .Build();
>
>             await context.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
>         }
>     };
> });
> ```

***

## 追加リソース

> [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 Communityでサポートを受ける

***

## よくある問題

> [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 に接続できるよう、アプリケーションからインターネットにアクセスできる
> * ドメイン形式がテナントのリージョンと一致している (`.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(...);
> ```

***

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

SDK のソースコードとあわせて、サンプルアプリケーションも用意されています。

> [card] [ASP.NET Core MVC Playgroud アプリ](https://github.com/auth0/auth0-aspnetcore-authentication/tree/main/playground/Auth0.AspNetCore.Authentication.Playground)
>
> ログイン、ログアウト、ユーザープロファイルなどの例が含まれています。

クローンして実行するには:

```bash theme={null}
git clone https://github.com/auth0/auth0-aspnetcore-authentication.git
cd auth0-aspnetcore-authentication/playground/Auth0.AspNetCore.Authentication.Playground
# appsettings.jsonをAuth0の設定で更新する
dotnet run
```

***
