Udostępnij przez


Uzyskiwanie tokenów użytkownika dla agentów interakcyjnych

Gdy agent interakcyjny uzyska autoryzację użytkownika, musi zażądać tokenów dostępu, które mogą służyć do wywoływania interfejsów API w imieniu użytkownika. W tym artykule opisano implementację przepływu On-Behalf-Of (OBO) w celu uzyskania delegowanych tokenów dostępu dla agenta interaktywnego.

Przepływ OBO umożliwia korzystanie z internetowego interfejsu API:

  • Odbieranie tokenu dostępu od klienta.
  • Wymień go na nowy token dostępu dla podrzędnego interfejsu API, takiego jak Microsoft Graph.
  • Użyj tego nowego tokenu, aby uzyskać dostęp do chronionych zasobów w imieniu oryginalnego użytkownika.

Wymagania wstępne

Przed zażądaniem tokenów użytkownika upewnij się, że masz:

Żądanie tokenów użytkownika

Przepływ OBO można zaimplementować ręcznie, postępując zgodnie z protokołem, zalecamy użycie Microsoft.Identity.Web biblioteki, co upraszcza implementację.

  1. Zainstaluj wymagany pakiet NuGet:

    dotnet add package Microsoft.Identity.Web
    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. W projekcie podstawowego internetowego interfejsu API ASP.NET zaktualizuj implementację uwierzytelniania identyfikatora Entra firmy Microsoft.

    // Program.cs
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.Identity.Abstractions;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Web.Resource;
    using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // With Microsoft.Identity.Web
    builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi();
    builder.Services.AddAgentIdentities();
    builder.Services.AddInMemoryTokenCaches();
    
    var app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.Run();
    
  3. W interfejsie API agenta wymień przychodzący token dostępu na nowy token dostępu dla tożsamości agenta. Microsoft.Identity.Web zajmuje się weryfikacją przychodzącego tokenu dostępu, ale obecnie nie jest aktualizowany w celu obsługi wymiany tokenów w imieniu użytkownika.

    app.MapGet("/agent-obo-user", async (HttpContext httpContext) =>
    {
       string agentid = "<your-agent-identity>";
        // Get the service to call the downstream API (preconfigured in the appsettings.json file)
        IAuthorizationHeaderProvider authorizationHeaderProvider = httpContext.RequestServices.GetService<IAuthorizationHeaderProvider>()!;
        AuthorizationHeaderProviderOptions options = new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentid);
    
        // Request user token for the agent identity
        string authorizationHeaderWithUserToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(["https://graph.microsoft.com/.default"], options);
    
        var response = new { header = authorizationHeaderWithUserToken };
        return Results.Json(response);
    })
    .RequireAuthorization();
    

Korzystanie z zestawu Microsoft Graph SDK

Jeśli używasz zestawu Microsoft Graph SDK, możesz uwierzytelnić się w programie Microsoft Graph przy użyciu programu GraphServiceClient.

  1. Zainstaluj element *Microsoft.Identity.Web.GraphServiceClient, który obsługuje uwierzytelnianie dla zestawu Graph SDK

    dotnet add package Microsoft.Identity.Web.GraphServiceClient
    
  2. W projekcie podstawowego internetowego interfejsu API ASP.NET dodaj obsługę programu Microsoft Graph w kolekcji usług.

    services.AddMicrosoftGraph();
    
  3. Pobierz element GraphServiceClient od dostawcy usług i używając tożsamości agenta, wywołaj interfejsy API programu Microsoft Graph.

    app.MapGet("/agent-obo-user", async (HttpContext httpContext) =>
    {
    
        string agentIdentity = "<your-agent-identity>";
        builder.Services.AddMicrosoftGraph();
    
        GraphServiceClient graphServiceClient = httpContext.RequestServices.GetService<GraphServiceClient>()!;
        var me = await graphServiceClient.Me.GetAsync(r => r.Options.WithAuthenticationOptions(
            o =>
            {
                o.WithAgentIdentity(agentIdentity);
            }));
        return me.UserPrincipalName;
    })