> ## 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 を使用して、新規または既存の ASP.NET MVC アプリケーションに Auth0 を統合する方法を紹介します。

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

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

<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-quickstart --skill auth0-aspnetcore-authentication
  ```

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

  ```text theme={null}
  Add Auth0 authentication to my ASP.NET Core MVC app
  ```

  AI アシスタントが Auth0 アプリケーションを自動的に作成し、認証情報を取得して、Auth0 ASP.NET Core Authentication SDK をインストールし、認証ミドルウェアを構成して、ログイン/ログアウト フローを実装します。[agent skills の詳細なドキュメント →](/ja/docs/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 を新規または既存の ASP.NET MVC アプリケーションに統合する方法を説明します。

<Steps>
  <Step title="新しいプロジェクトを作成" stepNumber={1}>
    このクイックスタート用に新しい ASP.NET Core MVC プロジェクトを作成する

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

    プロジェクトを開く

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

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

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

    CLIコマンドを実行して自動的に行う方法と、Dashboardから手動で行う方法のいずれかを選択できます。

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

        <Tabs>
          <Tab title="Mac/Linux">
            ```shellscript theme={null}
            AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && rm auth0-app-details.json && cat > appsettings.json << EOF
            {
              "Logging": {
                "LogLevel": {
                  "Default": "Information",
                  "Microsoft.AspNetCore": "Warning"
                }
              },
              "AllowedHosts": "*",
              "Auth0": {
                "Domain": "${DOMAIN}",
                "ClientId": "${CLIENT_ID}",
                "ClientSecret": "${CLIENT_SECRET}"
              }
            }
            EOF
            echo "appsettings.json created with your Auth0 details:" && cat appsettings.json
            ```
          </Tab>

          <Tab title="Windows (PowerShell)">
            ```powershell theme={null}
            $AUTH0_APP_NAME = "My MVC App"
            $latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/auth0/auth0-cli/releases/latest"
            $latestVersion = $latestRelease.tag_name
            $version = $latestVersion -replace "^v"
            Invoke-WebRequest -Uri "https://github.com/auth0/auth0-cli/releases/download/${latestVersion}/auth0-cli_${version}_Windows_x86_64.zip" -OutFile ".\auth0.zip"
            Expand-Archive ".\auth0.zip" .\
            [System.Environment]::SetEnvironmentVariable('PATH', $Env:PATH + ";${pwd}")
            auth0 login --no-input
            auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" | Set-Content -Path auth0-app-details.json
            $AppDetails = Get-Content -Raw auth0-app-details.json | ConvertFrom-Json
            $ClientId = $AppDetails.client_id
            $ClientSecret = $AppDetails.client_secret
            $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name
            $Config = Get-Content -Raw appsettings.json | ConvertFrom-Json
            if (-not $Config.Auth0) { $Config | Add-Member -MemberType NoteProperty -Name Auth0 -Value @{} }
            $Config.Auth0.Domain = $Domain
            $Config.Auth0.ClientId = $ClientId
            $Config.Auth0.ClientSecret = $ClientSecret
            $Config | ConvertTo-Json -Depth 10 | Set-Content appsettings.json
            Remove-Item auth0-api-details.json
            Write-Output "✅ appsettings.json updated with your Auth0 API details:"
            Get-Content appsettings.json
            ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab title="ダッシュボード">
        始める前に、プロジェクトのルートディレクトリに `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 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** の値に置き換えます
      </Tab>
    </Tabs>

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

    **Settings** タブで、次のURLを設定します。

    * **Allowed Callback URLs**: `http://localhost:5000/callback`
    * **許可されたログアウト URL**: `http://localhost:5000`
    * **許可された Web オリジン**: `http://localhost:5000`

    **Save Changes** をクリックします

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

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

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

  <Step title="ログイン機能とログアウト機能を追加" stepNumber={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();
        }
    }
    ```
  </Step>

  <Step title="ユーザープロファイル作成ビュー" stepNumber={6}>
    新しいファイル `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>
    ```

    <Info>
      **注:** `Views/Account` ディレクトリが存在しない場合は、先に作成する必要があります。
    </Info>
  </Step>

  <Step title="レイアウトを更新" stepNumber={7}>
    レイアウト ファイルを更新して、ログイン/ログアウト ボタンを追加します。`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>
    ```

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

  <Step title="アプリケーションを実行する" stepNumber={8}>
    ```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>
  **チェックポイント**

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

***

<div id="advanced-usage">
  ## 高度な使用法
</div>

<Accordion title="ユーザープロファイル情報にアクセスする">
  コントローラーまたはビューの `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);
  }
  ```

  ユーザーの claims には、標準的な OIDC 情報が含まれます。

  * **Name**: ユーザーの表示名
  * **Email**: ユーザーのメールアドレス
  * **Picture**: ユーザーのプロフィール画像の URL
  * **NameIdentifier** (sub): 一意のユーザー ID
</Accordion>

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

  ```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>

<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";
  });
  ```

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

  ```csharp Controllers/ApiController.cs theme={null}
  [Authorize]
  public async Task<IActionResult> CallApi()
  {
      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();
      
      return View(data);
  }
  ```
</Accordion>

<Accordion title="認証イベントを処理する">
  イベントを処理して、認証の動作をカスタマイズします。

  ```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);
          }
      };
  });
  ```
</Accordion>

***

<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="common-issues">
  ## よくある問題
</div>

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

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

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

    また、次の点も確認してください。

    * ドメイン値の末尾にスラッシュが付いていないこと
    * アプリケーションから Auth0 にアクセスできるインターネット接続があること
    * ドメイン形式がテナントのリージョン (`.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="sample-application">
  ## サンプルアプリケーション
</div>

SDK のソースコードとあわせて、サンプルアプリケーションを利用できます。

<Card title="ASP.NET Core MVC プレイグラウンド アプリ" icon="github" href="https://github.com/auth0/auth0-aspnetcore-authentication/tree/main/playground/Auth0.AspNetCore.Authentication.Playground">
  ログイン、ログアウト、ユーザープロファイルなどの例が含まれています。
</Card>

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

```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
```

***
