从 asp.net 核心身份验证 Web 应用获取 Microsoft Graph 的访问令牌

Getting Access Token for Microsoft Graph from asp.net core Authentication web app

我有一个应用程序可以根据 Azure AD 对用户进行身份验证:

Startup.cs

using Microsoft.AspNetCore.Authentication.Cookies;

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddAuthentication(
        SharedOptions => SharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

    services.AddAuthorization(options =>
    {
        //Auth Policies using group claims
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //loggerFactory

    app.UseCookieAuthentication();

    app.UseOpenIdConnectAtuhentication(new OpenIdConnectOptions
    {
        ClientID = Configuration["Authentication:AzureAd:ClientId"],
        Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
        CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"]
    });

    //Mvc Routing
}

AccountController.cs

 [HttpGet]
 public IActionResult SignIn()
 {
     return Challenge(
         new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
 }

在我想保护的控制器上,我然后使用 [Authorize(Policy = "Whatever")]

所有这些都运行良好,所以我的问题是我已经拥有的 cookie 是否包含我需要的令牌,如果是,我是简单地使用 User.Claims 之类的东西访问它还是我需要IAuthenticationProvider 按照 .net 4.6 示例中的方式设置 Here

如果是后者,我该怎么做而不像他们那样使用 Owin?

我应该补充一点,虽然授权工作正常,但我现在想做的事情包括列出一个 OU 中的所有用户。为此,据我所知,我必须访问 Microsoft Graph。也许,我的方向完全错了?

您可以使用 ADAL 获取访问令牌。您可以在这里找到一个很好的示例应用程序:https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore.

这是检索令牌的特别重要的部分:https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore/blob/master/WebApp-WebAPI-OpenIdConnect-DotNet/Startup.cs#L100

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

您从 Azure AD 获得授权代码,您需要将其交换为要调用的 API 的一个或多个访问令牌。对于 Microsoft Graph,请确保将资源 URI 设置为 https://graph.microsoft.com(示例针对 Azure AD Graph API)。

然后您可以调用 API,如下所示:https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore/blob/master/WebApp-WebAPI-OpenIdConnect-DotNet/Controllers/TodoController.cs#L31

            string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
            ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
            result = await authContext.AcquireTokenSilentAsync(Startup.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

result 包含您需要附加到 HTTP 请求的访问令牌。将从会话缓存中静默检索。

我想指出,整个过程在 ASP.NET Core 2.0 中要容易得多。那里的 Open Id Connect 身份验证处理程序实际上可以为您检索令牌。