Delen via


Zelfstudie: Een beveiligd eindpunt implementeren in uw API

In deze zelfstudie leert u hoe u een API-eindpunt beveiligt door verificatie-elementen toe te voegen aan de broncode. Het beveiligen van een API-eindpunt zorgt ervoor dat alleen geautoriseerde gebruikers toegang hebben. U kunt de API testen met een niet-geverifieerde aanvraag om ervoor te zorgen dat uw API de toegang beperkt tot onbevoegde gebruikers. Het Microsoft Identity Platform biedt een manier om API-eindpunten te beveiligen met behulp van het NuGet-pakket Microsoft.Identity.Web . In dit artikel, u;

  • Verificatie-elementen implementeren in de broncode
  • Weerinformatie voor de API toevoegen om weer te geven
  • De API testen met een niet-geverifieerde GET-aanvraag

Vereisten

Autorisatie implementeren

  1. Open het Program.cs-bestand en vervang de inhoud door het volgende codefragment:

    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);
    } 
    

De toepassing testen

  1. Selecteer in Visual Studio Starten zonder foutopsporing.

Op de webpagina http://localhost:{host} wordt een uitvoer weergegeven die vergelijkbaar is met de volgende afbeelding. Dit komt doordat de API zonder verificatie wordt aangeroepen. Als u een geautoriseerde aanroep wilt maken, raadpleegt u volgende stappen voor instructies voor het openen van een beveiligde web-API.

Schermopname van de fout 401 wanneer de webpagina wordt gestart.

Volgende stappen