教學課程:對 API 實作受保護的端點

在本教學課程中,您會瞭解如何將驗證元素新增至原始程式碼來保護 API 端點。 保護 API 端點可確保只允許授權的使用者存取。 您可以使用未經驗證的要求來測試 API,以確保您的 API 會限制未經授權使用者的存取權。 Microsoft 身分識別平台 提供使用 Microsoft.Identity.Web NuGet 套件來保護 API 端點的方法。 在本文中,您會;

  • 將驗證元素實作至原始程式碼
  • 新增要顯示之 API 的天氣資訊
  • 使用未經驗證的 GET 要求測試 API

必要條件

  • 完成教學課程:建立和設定 ASP.NET 核心專案以進行驗證的必要條件和步驟。

實作授權

  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 中,選取 [ 啟動但不偵錯]。

網頁 http://localhost:{host} 會顯示類似下圖的輸出。 這是因為 API 是在未驗證的情況下呼叫。 若要進行授權的呼叫,請參閱 後續步驟 ,以取得如何存取受保護Web API的作法指南。

顯示網頁啟動時 401 錯誤的螢幕快照。

下一步