在 ASP.NET Core 2.0 AzureAD 中获取 GraphService 访问令牌

Getting GraphService accesstoken in ASP.NET Core 2.0 AzureAD

我目前正在尝试在我的应用程序启动时自动设置图形服务。我有以下代码:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(options =>
            {
                Configuration.Bind("AzureAd", options);
            })
        .AddCookie();

        services.AddMvc();
    }

在 AddAzureAd 内部或之后我想注册并配置一个 GraphService 以连接到 MS AAD Graph Api https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api

但我不知道如何获得每个示例都提到的 accesstoken。我在 Graph API 的模板 "Read" 上勾选了方框,所以虽然这会自动配置,但遗憾的是它不是。

要使用 OpenIdConnect 协议在 asp.net 核心中获取访问令牌,我们需要使用 OnAuthorizationCodeReceived 事件,如下代码所示:

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = ClientId,
    Authority = Authority,
    PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    GetClaimsFromUserInfoEndpoint = false,

    Events = new OpenIdConnectEvents
    {
        OnRemoteFailure = OnAuthenticationFailed,
        OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
    }
});  

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{


       // Acquire a Token for the Graph API and cache it using ADAL.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
        string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
        AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);

        // Notify the OIDC middleware that we already took care of code redemption.
        context.HandleCodeRedemption();
}

关于在asp.net核心中获取access_token的更多细节,您可以参考下面的代码示例:

active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore