Skip to content

Azure Entra認証によるScalarの設定

概要

ASP.NET Core Web APIとMicrosoft Entra認証を統合する際、Scalar(Swaggerの後継)で認証済みAPIをテストする方法について説明します。このガイドでは、OAuth 2.0認証フローを設定し、Scalar UIから保護されたAPIエンドポイントにアクセスする方法を詳解します。

前提条件

  • ASP.NET Core 9 Web API
  • Microsoft Entra ID(旧Azure Active Directory)
  • Scalarパッケージ(Microsoft.OpenApiまたはScalarのASP.NETパッケージ)
  • Blazor WebAssemblyフロントエンド(認証済み)

OpenAPI設定の構成

まず、OpenAPI設定にOAuth 2.0セキュリティスキームを追加します。

csharp
// Program.cs
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Components ??= new OpenApiComponents();

        // OAuth 2.0セキュリティスキームの追加
        document.Components.SecuritySchemes.Add(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Flows = new OpenApiOAuthFlows
            {
                AuthorizationCode = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{builder.Configuration["AzureAD:TenantId"]}/oauth2/v2.0/authorize"),
                    TokenUrl = new Uri($"https://login.microsoftonline.com/{builder.Configuration["AzureAD:TenantId"]}/oauth2/v2.0/token"),
                    Scopes = new Dictionary<string, string>
                    {
                        {builder.Configuration["AzureAd:Scopes"], "データアクセス"}
                    },
                    // PKCEのデフォルト選択を許可
                    Extensions = new Dictionary<string, IOpenApiExtension>()
                    {
                        ["x-usePkce"] = new OpenApiString("SHA-256")
                        // クライアントシークレットの事前入力(オプション):
                        // [ "clientSecret" ] = new OpenApiString("<your-secret>")
                    }
                }
            }
        });

        // すべての操作に対するセキュリティ要件の提供
        document.SecurityRequirements.Add(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = JwtBearerDefaults.AuthenticationScheme
                    }
                },
                new[] { builder.Configuration["AzureAd:Scopes"] }
            }
        });

        return Task.CompletedTask;
    });
});

重要

クライアントシークレットをハードコーディングせず、安全な設定ソース(ユーザーシークレット、Key Vaultなど)から取得してください。

Scalarの設定

次に、Scalar APIリファレンスをマップし、認証オプションを設定します。

csharp
// Program.cs
app.MapScalarApiReference(options =>
{
    options.Authentication = new ScalarAuthenticationOptions
    {
        PreferredSecurityScheme = JwtBearerDefaults.AuthenticationScheme,
        OAuth2 = new OAuth2Options
        {
            ClientId = builder.Configuration["AzureAd:ClientId"],
            Scopes = [builder.Configuration["AzureAd:Scopes"]]
        }
    };
});

Entra IDの設定

1. リダイレクトURLの追加

Entra IDのアプリ登録で、ScalarのリダイレクトURLを追加します:

  1. Azureポータルでアプリ登録を開く
  2. 「認証」セクションに移動
  3. 「プラットフォームを追加」→「シングルページアプリケーション」
  4. リダイレクトURIを追加:https://localhost:<port>/scalar/v1

2. スコープの設定

APIアプリ登録でスコープを公開します:

  1. APIアプリ登録を開く
  2. 「APIの公開」セクションに移動
  3. スコープを追加(例:api://<client-id>/data.read

スコープ形式

スコープは通常 api://<client-id>/<scope-name> の形式です。このスコープをOpenAPI設定とScalar設定の両方で使用します。

3. エンドポイントの確認

エンドポイントが正しく設定されていることを確認します:

  • 認証エンドポイント: https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/authorize
  • トークンエンドポイント: https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token

注意

https://login.microsoftonline.com/common で始まるエンドポイントではなく、テナントIDを含む具体的なエンドポイントを使用してください。

一般的な問題の解決

権限エラー (401)

  • スコープが正しく設定されているか確認
  • リダイレクトURIがアプリ登録に追加されているか確認
  • クライアントIDとテナントIDが正しいか確認

IDX10511 エラー

トークン検証の署名エラーが発生する場合:

  1. APIアプリ登録で「マニフェスト」を開く
  2. accessTokenAcceptedVersion2 に設定
  3. トークンの対象ユーザー(audience)が正しいか確認

まとめ

この設定により、Scalar UIからMicrosoft Entra IDで保護されたAPIエンドポイントをテストできるようになります。Scalarの認証セクションでOAuth 2.0フローを選択し、認証ボタンをクリックすることで、ベアラートークンが自動的にリクエストに追加されます。

この設定は、開発環境でのAPIテストを大幅に簡素化し、本番環境と同様の認証フローを体験できます。

最新情報

Scalarのドキュメントは頻繁に更新されます。最新情報は公式ガイドを参照してください。