次の方法で共有


チュートリアル: 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 エラーを示すスクリーンショット。

次の手順

方法: cURL を使用して API を呼び出す