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

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

> このガイドでは、Microsoft.Owin.Security.OpenIdConnect NuGet パッケージを使用して、新規または既存の ASP.NET OWIN アプリケーションに Auth0 を統合する方法を説明します。

Auth0 を使用すると、ASP.NET OWIN アプリケーションに数分で認証を追加できます。このガイドでは、従来の ASP.NET OWIN アプリケーションにログイン、ログアウト、ユーザープロファイルの表示を追加する方法を説明します。

このガイドを終えると、アプリケーションで次のことができるようになります。

* ユーザーがサインインすると Auth0 Universal Login にリダイレクトされる
* コールバックを処理し、セッションを Cookie に保存する
* 認証されたユーザーの名前、メールアドレス、プロフィール画像を表示する
* アプリケーションと Auth0 の両方からユーザーをサインアウトする

このガイドは、OWIN を使用する **従来の ASP.NET (.NET Framework) ** アプリケーションを対象としています。アプリケーションがすでに **ASP.NET Core** で動作している場合は、代わりに [`Auth0.AspNetCore.Authentication`](/docs/docs/ja-jp/quickstart/webapp/aspnet-core) SDK を使用してください。

## 前提条件

始める前に、次のものを用意してください。

* Auth0 アカウント - [無料で登録](https://auth0.com/signup)
* OWIN が有効になっている .NET Framework 対応の既存の ASP.NET MVC アプリケーション、または Visual Studio の **ASP.NET Web Application (.NET Framework) → MVC** テンプレートから新規作成したアプリケーション
* [Visual Studio 2019 以降](https://visualstudio.microsoft.com/) (または .NET Framework MVC プロジェクトをサポートする任意の IDE)

## ステップ

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

Auth0を使用するすべてのアプリケーションは、Auth0 Dashboardに登録する必要があります。Auth0は**Client ID**と**ドメイン**を発行します。アプリはこれらを使用してAuth0と通信します。

CLI コマンドを実行して Auth0 アプリを自動的に設定するか、Auth0 Dashboardから手動で設定するかを選択できます。

> [tab] CLI
>
> プロジェクトのルートディレクトリで次のコマンドを実行し、Auth0 アプリケーションを作成して `Web.config` の値を生成します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLIをインストールします（まだインストールされていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0アプリを設定し、Web.configの値を生成します
> auth0 qs setup --app --type regular --framework aspnet-owin --port 5000 --name "My OWIN App"
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLIをインストールします（まだインストールされていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0アプリを設定し、Web.configの値を生成します
> auth0 qs setup --app --type regular --framework aspnet-owin --port 5000 --name "My OWIN App"
> ```
>
> > [!NOTE]
> >
> > このコマンドは次の処理を行います:
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. `http://localhost:5000` 用に設定された Auth0 Regular Web Application を作成します
> > 3. `auth0:Domain`、`auth0:ClientId`、`auth0:ClientSecret` を含む `Web.config` の値を生成します

> [tab] Dashboard
>
> 1. [Auth0 Dashboard → アプリケーション](https://manage.auth0.com/#/applications) に移動します。
> 2. **Create Application** をクリックします。
> 3. アプリケーションの名前を入力します (例: `My OWIN App`) 。
> 4. アプリケーションタイプとして **Regular Web Application** を選択し、**Create** をクリックします。
> 5. **Settings** タブに移動し、次の URL を設定します。
>
> | 設定 | 値 |
> | - | - |
> | **Allowed Callback URLs** | `http://localhost:3000/callback` |
> | **Allowed Logout URLs** | `http://localhost:3000/` |
> | **Allowed Web Origins** | `http://localhost:3000` |
>
> 6. **Save Changes** をクリックします。
> 7. **Basic Information** セクションから **Domain** と **Client ID** をコピーし、`Web.config` に追加します。
>
> ```xml Web.config theme={null}
> <?xml version="1.0" encoding="utf-8"?>
> <configuration>
>   <appSettings>
>     <add key="auth0:Domain" value="{yourDomain}" />
>     <add key="auth0:ClientId" value="{yourClientId}" />
>   </appSettings>
> </configuration>
> ```

> [!NOTE]
>
> アプリを別のポートで実行している場合は、上記のすべてのURLの `3000` を実際のポート番号に置き換えてください。

**2. NuGet パッケージをインストール**

必要な 2 つの OWIN ミドルウェア パッケージをプロジェクトに追加します。

| Package | Purpose |
| - | - |
| `Microsoft.Owin.Security.OpenIdConnect` | Auth0 との OpenID Connect (OIDC) 認証フローを処理します |
| `Microsoft.Owin.Security.Cookies` | ログイン後のユーザー セッションをブラウザーの cookie に保持します |

> [tab] パッケージ マネージャー コンソール
>
> Visual Studio で **Package Manager Console** (`Tools → NuGet Package Manager → Package Manager Console`) を開き、次を実行します。
>
> ```powershell theme={null}
> Install-Package Microsoft.Owin.Security.OpenIdConnect
> Install-Package Microsoft.Owin.Security.Cookies
> ```

> [tab] dotnet CLI
>
> プロジェクトのディレクトリから、次を実行します。
>
> ```bash theme={null}
> dotnet add package Microsoft.Owin.Security.OpenIdConnect
> dotnet add package Microsoft.Owin.Security.Cookies
> ```

> [!NOTE]
>
> OWIN cookie middleware を `System.Web` の cookie と併用すると、問題が発生することがあります。cookie が二重に設定される問題が発生した場合は、[System.Web cookie integration issues](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues) のガイダンスを参照してください。

**3. OWIN ミドルウェアを設定する**

OWIN ミドルウェアはスタートアップ クラスで登録します。プロジェクトにすでに OWIN のスタートアップ クラス (通常は `App_Start/Startup.Auth.cs`) がある場合は、その `ConfigureAuth` メソッドを更新してください。ない場合は、このファイルを作成してください。

**cookie middleware** と **OpenID Connect middleware** の両方が必要で、必ず次の順序で登録する必要があります。

1. Cookie middleware - 認証済みユーザーのセッションを保存します
2. OpenID Connect middleware - Auth0 のログイン フローとログアウト フローを処理します

```csharp App_Start/Startup.Auth.cs theme={null}
using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        var domain = ConfigurationManager.AppSettings["auth0:Domain"];
        var clientId = ConfigurationManager.AppSettings["auth0:ClientId"];

        // Cookie middleware は最初に登録する必要があります
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationType = "Auth0",
            Authority = $"https://{domain}",
            ClientId = clientId,
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            Scope = "openid profile email",
            TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = "name"
            },
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = notification =>
                {
                    if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                    {
                        // Auth0 のログアウト URL を生成してリダイレクトします
                        var logoutUri = $"https://{domain}/v2/logout?client_id={clientId}";
                        notification.Response.Redirect(logoutUri);
                        notification.HandleResponse();
                    }

                    return Task.FromResult(0);
                }
            }
        });
    }
}
```

`ConfigureAuth` が `Startup.cs` の `Configuration` メソッドから呼び出されるようにしてください：

```csharp Startup.cs theme={null}
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}
```

`AuthenticationType` は `"Auth0"` に設定されています。この文字列は、次のステップでログインチャレンジをトリガーする際に使用されます。`RedirectToIdentityProvider` 通知はログアウト リクエストを捕捉し、適切な Auth0 のログアウト URL を生成します。

**4. ログイン、ログアウト、プロファイルのアクションを追加する**

`Login`、`Logout`、`UserProfile` の 3 つのアクションを含む `Controllers/AccountController.cs` を作成します。

```csharp Controllers/AccountController.cs theme={null}
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Auth0.AspNetCore.Authentication;

public class AccountController : Controller
{
  public ActionResult Login(string returnUrl = "/")
  {
    HttpContext.GetOwinContext().Authentication.Challenge(
      new AuthenticationProperties
      {
          RedirectUri = returnUrl ?? Url.Action("Index", "Home")
      },
      "Auth0"
    );
  }

  [Authorize]
  public ActionResult UserProfile()
  {
      var claimsIdentity = User.Identity as ClaimsIdentity;
      return View(new UserProfileViewModel()
      {
          Name = claimsIdentity?
            .FindFirst(c => c.Type == claimsIdentity.NameClaimType)?.Value,
          EmailAddress = claimsIdentity?
            .FindFirst(c => c.Type == ClaimTypes.Email)?.Value,
          ProfileImage = claimsIdentity?
            .FindFirst(c => c.Type == "picture")?.Value
      });
  }

  [Authorize]
  public void Logout()
  {
    HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
    HttpContext.GetOwinContext().Authentication.SignOut("Auth0");
  }
}
```

**各アクションの動作:**

* **`Login`** - `"Auth0"` スキームで `Challenge` を呼び出します。OIDC ミドルウェアがこれを捕捉し、ユーザーを Auth0 Universal Login にリダイレクトします。サインインに成功すると、ユーザーは `returnUrl` にリダイレクトされます。
* **`UserProfile`** - `ClaimsIdentity` から認証済みユーザーの claims を読み取り、`UserProfileViewModel` を介してビューに渡します。`[Authorize]` 属性により、未認証のユーザーはまずログインにリダイレクトされます。
* **`Logout`** - `SignOut` を 2 回呼び出します。1 回目はローカルの Cookie セッションをクリアするため、2 回目はユーザーを Auth0 からサインアウトするためです (これにより、アクティブな SSO セッションも終了します) 。

プロファイル データを保持する `Models/UserProfileViewModel.cs` を作成します:

```csharp Models/UserProfileViewModel.cs theme={null}
public class UserProfileViewModel
{
    public string Name { get; set; }
    public string EmailAddress { get; set; }
    public string ProfileImage { get; set; }
}
```

> [!NOTE]
>
> ##### チェックポイント
>
> アプリケーションを実行し、`/Account/Login` にアクセスします。Auth0 Universal Login ページにリダイレクトされるはずです。サインイン後は、アプリケーションのホームページにリダイレクトされて戻ります。Redirect URI エラーが表示される場合は、Auth0 アプリケーションの設定にある callback URL が、アプリケーションの実行 URL と完全に一致していることを確認してください。

**5. プロファイルビューを追加する**

ログイン中のユーザー情報を表示するために、`Views/Account/UserProfile.cshtml` を作成します:

```cshtml Views/Account/UserProfile.cshtml theme={null}
@model UserProfileViewModel
@{
    ViewBag.Title = "User Profile";
}

<h2>User Profile</h2>

<div>
    <img src='@Model.ProfileImage'
         alt="Profile picture"
         style="max-width:120px; border-radius:60px;" />
</div>

<ul>
    <li><strong>Name:</strong> @Model.Name</li>
    <li><strong>Email:</strong> @Model.EmailAddress</li>
</ul>
```

ビューは、Auth0 が ID トークンを返したときに OIDC ミドルウェアが抽出したクレームをもとに生成された `UserProfileViewModel` を受け取ります。

> [!NOTE]
>
> ##### チェックポイント
>
> ログイン後、`/Account/UserProfile` に移動します。名前、メールアドレス、プロフィール画像が表示されるはずです。名前またはメールアドレスが空の場合は、`OpenIdConnectAuthenticationOptions` の `Scope` に `"openid profile email"` が含まれていることを確認してください。

**6. レイアウトにログインとログアウトのリンクを追加する**

ユーザーの認証状態に応じてログインリンクとログアウトリンクが表示されるよう、`Views/Shared/_Layout.cshtml` を更新します。

```cshtml Views/Shared/_Layout.cshtml theme={null}
@if (User.Identity.IsAuthenticated)
{
    <a href="@Url.Action("UserProfile", "Account")">@User.Identity.Name</a>
    <a href="@Url.Action("Logout", "Account")">Log out</a>
}
else
{
    <a href="@Url.Action("Login", "Account")">Log in</a>
}
```

レイアウト内でナビゲーションリンクを表示している箇所の `<nav>` 要素内に、これを追加します。

> [!NOTE]
>
> ##### チェックポイント
>
> アプリケーションを実行します。ナビゲーションに **ログイン** リンクが表示されるはずです。サインインすると、それがあなたの名前 (プロファイルへのリンク) と **ログアウト** リンクに変わるはずです。**ログアウト** をクリックするとサインアウトされ、ホームページに戻るはずです。

> [!TIP]
>
> これで、ASP.NET OWIN アプリケーションで動作する Auth0 連携を利用できるようになりました。ユーザーは Auth0 Universal Login を通じてログインし、自分のプロファイルを表示して、ログアウトできます。

## よくある問題

> [accordion] ログイン後の Redirect URI の不一致
>
> **問題:** ユーザーのサインイン後に、Auth0 で "redirect\_uri mismatch" または "callback URL mismatch" エラーが表示されます。
>
> **解決策:** アプリが Auth0 に送信する Redirect URI は、Auth0 アプリケーション設定の **Allowed Callback URLs** のいずれかと完全に一致している必要があります。プロトコル (`http` と `https`) 、ポート番号、パス、末尾のスラッシュの違いを確認してください。

> [accordion] ログイン ループ — アプリが Auth0 にリダイレクトされ続ける
>
> **問題:** サインインに成功した後、認証済みのページが表示されず、すぐに Auth0 にリダイレクトされます。
>
> **解決策:** ミドルウェアが正しい順序で登録されており、OWIN パイプラインが初期化されていることを確認してください。
>
> * cookie middleware は `ConfigureAuth` 内で OpenID Connect ミドルウェアより**前**に登録する必要があります。
> * `app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)` は `ConfigureAuth` 内で最初に呼び出す必要があります。
> * OWIN パイプラインが正しく初期化されるように、`[assembly: OwinStartup(typeof(Startup))]` 属性が存在している必要があります。
>
> ```csharp App_Start/Startup.Auth.cs theme={null}
> app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); // 最初に呼び出す必要があります
>
> app.UseCookieAuthentication(...);          // OIDC より前に Cookie middleware
> app.UseOpenIdConnectAuthentication(...);   // cookie の後に OIDC ミドルウェア
> ```

> [accordion] ログアウト後にユーザーがアプリへリダイレクトされない
>
> **問題:** **ログアウト**をクリックするとユーザーは Auth0 からサインアウトされますが、アプリケーションに戻りません。
>
> **解決策:** `RedirectToIdentityProvider` 通知で、Auth0 の logout URL に `returnTo` クエリパラメータを追加してください。戻り先 URL は、Auth0 アプリケーション設定の **Allowed Logout URLs** にも登録されている必要があります。
>
> ```csharp App_Start/Startup.Auth.cs theme={null}
> var logoutUri = $"https://{domain}/v2/logout?client_id={clientId}&returnTo={Uri.EscapeDataString("http://localhost:3000/")}";
> ```

> [accordion] プロフィール画像またはメールアドレスが空になる
>
> **問題:** ログイン後、`Model.ProfileImage` または `Model.EmailAddress` が null になります。
>
> **解決策:** `OpenIdConnectAuthenticationOptions` の `Scope` に `"openid profile email"` が含まれていることを確認してください。`profile` scope は名前とプロフィール画像を提供し、`email` scope はメールアドレスを提供します。
>
> ```csharp App_Start/Startup.Auth.cs theme={null}
> app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
> {
>     Scope = "openid profile email",  // 3 つの scope がすべて必要です
>     ...
> });
> ```

> [accordion] 起動時に Domain または Client ID の値が null になる
>
> **問題:** アプリケーションの起動時に null 参照または構成例外が発生します。
>
> **解決策:** `Web.config` の `<appSettings>` に `auth0:Domain` と `auth0:ClientId` の両方が存在すること、また、正しい `Web.config` 変換が読み込まれるビルド構成 (Debug/Release) で実行していることを確認してください。
>
> ```xml Web.config theme={null}
> <configuration>
>   <appSettings>
>     <add key="auth0:Domain" value="{yourDomain}" />     <!-- 空にしてはいけません -->
>     <add key="auth0:ClientId" value="{yourClientId}" /> <!-- 空にしてはいけません -->
>   </appSettings>
> </configuration>
> ```

## 高度な使い方

> [accordion] ログインパラメーターをカスタマイズする
>
> `Startup.Auth.cs` の `RedirectToIdentityProvider` 通知を変更すると、Auth0のログインページにカスタムパラメーターを渡せます。
>
> ```csharp App_Start/Startup.Auth.cs theme={null}
> RedirectToIdentityProvider = notification =>
> {
>     if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
>     {
>         // ログインではなくサインアップ画面を表示
>         notification.ProtocolMessage.SetParameter("screen_hint", "signup");
>
>         // 特定の UI ロケールを設定
>         notification.ProtocolMessage.SetParameter("ui_locales", "es");
>     }
>
>     return Task.FromResult(0);
> }
> ```

> [accordion] ユーザーに代わってAPIを呼び出す
>
> アクセストークンを使って API を呼び出すには、OIDC リダイレクト時に `audience` と必要な API スコープを要求します。
>
> ```csharp App_Start/Startup.Auth.cs theme={null}
> RedirectToIdentityProvider = notification =>
> {
>     if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
>     {
>         notification.ProtocolMessage.SetParameter("audience", "https://your-api.example.com");
>         notification.ProtocolMessage.Scope += " read:data";
>     }
>
>     return Task.FromResult(0);
> }
> ```
>
> 次に、認証済みユーザーのクレームからアクセストークンを取得します。
>
> ```csharp Controllers/ApiController.cs theme={null}
> [Authorize]
> public async Task<ActionResult> CallApi()
> {
>     var claimsIdentity = User.Identity as ClaimsIdentity;
>     var accessToken = claimsIdentity?.FindFirst("access_token")?.Value;
>
>     var client = new HttpClient();
>     client.DefaultRequestHeaders.Authorization =
>         new AuthenticationHeaderValue("Bearer", accessToken);
>
>     var response = await client.GetAsync("https://your-api.example.com/data");
>     // レスポンスを処理...
> }
> ```

***

## 追加リソース

> [card] [サンプルアプリケーション](https://github.com/auth0-samples/auth0-aspnet-owin-mvc-samples/tree/master/Quickstart/Sample)
>
> このQuickstartの完全な動作サンプル

> [card] [Katana / OWIN ドキュメント](https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/)
>
> Microsoft の公式 OWIN/Katana リファレンス

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