Share via


자습서: 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에서 디버깅하지 않고 시작을 선택합니다.

웹 페이지 http://localhost:{host}에는 다음 이미지와 유사한 출력이 표시됩니다. 인증 없이 API가 호출되기 때문입니다. 권한 부여된 호출을 하려면 보호된 웹 API에 액세스하는 방법에 대한 안내를 보려면 다음 단계를 참조하세요.

웹 페이지가 시작될 때 401 오류를 보여 주는 스크린샷.

다음 단계