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

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 Blazor Server app
AI アシスタントは、Auth0 アプリケーションの作成、認証情報の取得、Auth0 ASP.NET Core Authentication SDK のインストール、認証ミドルウェアの構成、ログイン/ログアウトフローの実装を自動的に行います。agent skills の完全なドキュメント →
前提条件: 始める前に、以下がインストールされていることを確認してください。

はじめに

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

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

このクイックスタート用に、新しい Blazor Server プロジェクトを作成します
dotnet new blazor -n SampleBlazorApp --interactivity Server
プロジェクトを開く
cd SampleBlazorApp
2

Auth0 SDKをインストールする

dotnet add package Auth0.AspNetCore.Authentication
3

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

次に、Auth0テナントで新しいアプリケーションを作成し、その設定をプロジェクトに追加します。CLIコマンドを実行して自動的に行う方法と、ダッシュボードから手動で行う方法のいずれかを選択できます。
Auth0 アプリケーションを作成し、appsettings.json を更新するには、プロジェクトのルートディレクトリで次のシェルコマンドを実行します。
AUTH0_APP_NAME="My Blazor 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

認証を設定する

Auth0 認証を構成するには、Program.cs を更新します。
Program.cs
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();
注: ミドルウェアの順序は重要です。UseAuthentication()UseAuthorization() より前に呼び出す必要があります。
5

ログインページとログアウトページを追加

ユーザーが認証できるように、ログイン ページとログアウト ページを作成します。まず、Pages フォルダーとファイルを作成します。
mkdir -p Pages && touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor
続いて、次のコード スニペットを追加します。
6

プロフィールページの作成とレイアウトの更新

ユーザーの名前とクレームを表示するカスタムユーザープロファイルページを作成し、レイアウトを更新してログイン/ログアウトのリンクを追加します。まず、Profile コンポーネントを作成します。
touch Components/Pages/Profile.razor
次のコードスニペットを追加します。MainLayout のコードは、レイアウトの先頭部分に追加し、それ以外の部分はそのまま残してください。
7

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

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

高度な使い方

Auth0 のログインページにカスタムパラメーターを渡せます。
Pages/Login.cshtml.cs
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);
}
ユーザーに代わって外部 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";
    options.UseRefreshTokens = true;
});
次に、アクセストークンを取得します。
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();
B2B シナリオ向けに組織のサポートを設定します。
Program.cs
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"];
});
または、ログイン時に組織を指定します。
Pages/Login.cshtml.cs
var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
    .WithOrganization("org_abc123")
    .WithRedirectUri("/")
    .Build();

よくある問題

問題: 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(...);

参考資料

GitHub リポジトリ

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

API リファレンス

詳細な API ドキュメント

コミュニティフォーラム

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

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

Auth0 と ASP.NET Core MVC の統合を示すサンプルアプリケーションを以下に示します。

ASP.NET Core Blazor アプリ

ログイン、ログアウト、ユーザープロファイルなどの例が含まれています。
クローンして実行します。
git clone https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample

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