다음을 통해 공유


대화형 에이전트에 대한 사용자 토큰 획득

대화형 에이전트가 사용자 권한 부여를 얻은 후에는 사용자를 대신하여 API를 호출하는 데 사용할 수 있는 액세스 토큰을 요청해야 합니다. 이 문서에서는 OBO(On-Behalf-Of) 흐름을 구현하여 대화형 에이전트에 대한 위임된 액세스 토큰을 가져오는 방법을 안내합니다.

OBO 흐름을 사용하면 웹 API에서 다음을 수행할 수 있습니다.

  • 클라이언트에서 액세스 토큰을 받습니다.
  • Microsoft Graph와 같은 다운스트림 API에 대한 새 액세스 토큰으로 교환합니다.
  • 새 토큰을 사용하여 원래 사용자를 대신하여 보호된 리소스에 액세스합니다.

필수 조건

사용자 토큰을 요청하기 전에 다음이 있는지 확인합니다.

사용자 토큰 요청

프로토콜을 따라 OBO 흐름을 수동으로 구현할 수 있지만 구현을 간소화하는 라이브러리를 사용하는 Microsoft.Identity.Web 것이 좋습니다.

  1. 필요한 NuGet 패키지를 설치합니다.

    dotnet add package Microsoft.Identity.Web
    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. ASP.NET 핵심 웹 API 프로젝트에서 Microsoft Entra ID 인증 구현을 업데이트합니다.

    // 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. 에이전트 API에서 들어오는 액세스 토큰을 에이전트 ID에 대한 새 액세스 토큰으로 교환합니다. Microsoft.Identity.Web 은 들어오는 액세스 토큰의 유효성 검사를 처리하지만 현재는 대신 토큰 교환을 처리하도록 업데이트되지 않습니다.

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

Microsoft Graph SDK 사용

Microsoft Graph SDK를 사용하는 경우 다음을 사용하여 GraphServiceClientMicrosoft Graph에 인증할 수 있습니다.

  1. Graph SDK에 대한 인증을 처리하는 *Microsoft.Identity.Web.GraphServiceClient 설치

    dotnet add package Microsoft.Identity.Web.GraphServiceClient
    
  2. ASP.NET 핵심 Web API 프로젝트에서 서비스 컬렉션에 Microsoft Graph에 대한 지원을 추가합니다.

    services.AddMicrosoftGraph();
    
  3. GraphServiceClient 서비스 공급자로부터 가져오기 및 에이전트 ID를 사용하여 Microsoft Graph API 호출

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