チュートリアル: API に保護されたエンドポイントを実装する

このチュートリアルでは、ソース コードに認証要素を追加して API エンドポイントを保護する方法について説明します。 API エンドポイントを保護することで、承認されたユーザーだけがアクセスを許可されます。 認証されていない要求を使用して API をテストして、承認されていないユーザーへのアクセスが API で制限されることを確認できます。 Microsoft ID プラットフォームは、Microsoft.Identity.Web NuGet パッケージを使用することで API エンドポイントを保護する方法を提供します。 この記事では、次のことを行います。

  • ソース コードに認証要素を実装する
  • 表示する API の気象情報を追加する
  • 認証されていない GET 要求で API をテストする

前提条件

承認を実装する

  1. Program.cs ファイルを開き、内容を次のスニペットに置き換えます。

    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(options =>
            {
                builder.Configuration.Bind("AzureAd", options);
                options.TokenValidationParameters.NameClaimType = "name";
            }, options => { builder.Configuration.Bind("AzureAd", options); });
    
        builder.Services.AddAuthorization(config =>
        {
            config.AddPolicy("AuthZPolicy", policyBuilder =>
                policyBuilder.Requirements.Add(new ScopeAuthorizationRequirement() { RequiredScopesConfigurationKey = $"AzureAd:Scopes" }));
        });
    
    // Add services to the container.
    builder.Services.AddRazorPages();
    
    var app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    var weatherSummaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
    
    app.MapGet("/weatherforecast", [Authorize(Policy = "AuthZPolicy")] () =>
        {
            var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateTime.Now.AddDays(index),
                    Random.Shared.Next(-20, 55),
                    weatherSummaries[Random.Shared.Next(weatherSummaries.Length)]
                ))
                .ToArray();
            return forecast;
        })
        .WithName("GetWeatherForecast");
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapRazorPages();
    
    app.Run();
    
    record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
    {
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    } 
    

アプリケーションをテストする

  1. Visual Studio で、[デバッグなしで開始] を選択します。

Web ページ http://localhost:{host} には、次の画像のような出力が表示されます。 これは、API が認証なしで呼び出されているためです。 承認された呼び出しを行うには、次の手順で保護された Web API にアクセスする方法についてのハウツー ガイドを参照してください。

Web ページが起動されたときの 401 エラーを示すスクリーンショット。

次のステップ