メインコンテンツへスキップ

AI で Auth0 を統合する

Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントをお使いの場合は、agent skills を使って数分で Auth0 認証を自動的に追加できます。インストール:
npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-aspnetcore-authentication
次に、AI アシスタントに次のように依頼します。
Add Auth0 authentication to my ASP.NET Core MVC app
AI アシスタントが Auth0 アプリケーションを自動的に作成し、認証情報を取得して、Auth0 ASP.NET Core Authentication SDK をインストールし、認証ミドルウェアを構成して、ログイン/ログアウト フローを実装します。agent skills の詳細なドキュメント →
前提条件: 開始する前に、次のものがインストールされていることを確認してください。

はじめに

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

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

このクイックスタート用に新しい ASP.NET Core MVC プロジェクトを作成する
dotnet new mvc -n SampleMvcApp
プロジェクトを開く
cd SampleMvcApp
2

Auth0 SDKをインストール

dotnet add package Auth0.AspNetCore.Authentication
3

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

次に、Auth0テナントで新しいアプリケーションを作成し、その設定をプロジェクトに追加します。CLIコマンドを実行して自動的に行う方法と、Dashboardから手動で行う方法のいずれかを選択できます。
プロジェクトのルートディレクトリで次のシェルコマンドを実行し、Auth0 アプリケーションを作成して appsettings.json を更新します。
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
コールバックURLを設定する:Settings タブで、次のURLを設定します。
  • Allowed Callback URLs: http://localhost:5000/callback
  • 許可されたログアウト URL: http://localhost:5000
  • 許可された Web オリジン: http://localhost:5000
Save Changes をクリックします
重要: 接続を設定し、Auth0 Dashboard の 接続 タブでその接続をアプリケーションに対して有効にしてください。
4

認証を設定する

Program.cs を更新して、Auth0 認証を構成します。
Program.cs
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 を作成します。
Controllers/AccountController.cs
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

ユーザープロファイル作成ビュー

新しいファイル Views/Account/Profile.cshtml を作成します。
Views/Account/Profile.cshtml
@{
    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>
注: Views/Account ディレクトリが存在しない場合は、先に作成する必要があります。
7

レイアウトを更新

レイアウト ファイルを更新して、ログイン/ログアウト ボタンを追加します。Views/Shared/_Layout.cshtml<nav> 要素を見つけ、次の内容に置き換えます。
Views/Shared/_Layout.cshtml
<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>
重要: 置き換えるのは <nav> 要素のみです。_Layout.cshtml のそれ以外の部分はすべてそのままにしてください。特に、ページ コンテンツのレンダリングに必要な @RenderBody() 呼び出しは必ず残してください。
8

アプリケーションを実行する

dotnet run
アプリケーションが起動し、リッスンしている URL が表示されるはずです:
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
ブラウザーを開いて http://localhost:5000 にアクセスします。ナビゲーションバーの Login リンクをクリックします。Auth0 のログインページにリダイレクトされます。ログインするとアプリケーションにリダイレクトされ、ナビゲーションバーに自分の名前が表示されます。
チェックポイントこれで、http://localhost:5000 で Auth0 によって保護された、完全に動作する MVC アプリケーションが実行されているはずです。ユーザーはログイン、ユーザープロファイルの表示、ログアウトを行えます。

高度な使用法

コントローラーまたはビューの User プロパティから、ユーザープロファイル情報にアクセスできます。
Controllers/AccountController.cs
[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
Auth0 のログインページにカスタムパラメーターを渡すことができます。
Controllers/AccountController.cs
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);
}
ユーザーに代わって外部 API を呼び出す必要がある場合は、トークンを取得して保存できます。
Program.cs
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";
});
次に、コントローラーでアクセストークンを取得します。
Controllers/ApiController.cs
[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);
}
イベントを処理して、認証の動作をカスタマイズします。
Program.cs
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);
        }
    };
});

その他のリソース

GitHub リポジトリ

ソースコードと Issue トラッカー

API リファレンス

詳細な API ドキュメント

コミュニティフォーラム

Auth0 コミュニティでサポートを受ける

よくある問題

問題: Unable to obtain configuration from: https://your-tenant.auth0.com/.well-known/openid-configuration解決策: ドメインが正しく、https:// が含まれていないことを確認してください。authority はライブラリによって自動的に構築されます。
{
  "Auth0": {
    "Domain": "your-tenant.auth0.com"  // 正しい - プロトコルなし
  }
}
また、次の点も確認してください。
  • ドメイン値の末尾にスラッシュが付いていないこと
  • アプリケーションから Auth0 にアクセスできるインターネット接続があること
  • ドメイン形式がテナントのリージョン (.auth0.com.us.auth0.com.eu.auth0.com) と一致していること
問題: ArgumentNullException: Value cannot be null. (Parameter 'Domain') または同様のエラー。解決策: appsettings.json に、Domain、ClientId、ClientSecret の値を含む Auth0 セクションがあることを確認してください。構成が正しく読み込まれていることも確認してください。
Program.cs
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");
});
問題: 構成が正しいにもかかわらず、認証が機能しない。解決策: ミドルウェアが正しい順序で配置されていることを確認してください。UseAuthentication()UseAuthorization() より前に配置する必要があります。
Program.cs
app.UseRouting();
app.UseAuthentication();  // UseAuthorization より前に配置する必要があります
app.UseAuthorization();
app.MapControllerRoute(...);

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

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

ASP.NET Core MVC プレイグラウンド アプリ

ログイン、ログアウト、ユーザープロファイルなどの例が含まれています。
クローンして実行します。
git clone https://github.com/auth0/auth0-aspnetcore-authentication.git
cd auth0-aspnetcore-authentication/playground/Auth0.AspNetCore.Authentication.Playground
# appsettings.jsonをAuth0の設定で更新する
dotnet run