c# - 从 asp.net core 身份验证 Web 应用程序获取 Microsoft Graph 的访问 token

标签 c# azure asp.net-core .net-core microsoft-graph-api

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

启动.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);
 }

在我想要保护的 Controller 上,我使用 [Authorize(Policy = "Whatever")]

所有这些都工作得很好,所以我的问题是我已经拥有的 cookie 是否包含我需要的 token ,如果是,我是否只需使用 User.Claims 之类的东西访问它,或者我是否需要 IAuthenticationProvider按照 .net 4.6 Here 示例中的方式进行设置.

如果是后者,我该如何在不使用 Owin 的情况下做到这一点?

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

最佳答案

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

这是检索 token 的特别重要的部分: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 的一个或多个访问 token 。对于 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 请求的访问 token 。它将从 session 缓存中静默检索。

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

关于c# - 从 asp.net core 身份验证 Web 应用程序获取 Microsoft Graph 的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336207/

相关文章:

c# - Tesseract OCR - 如何训练这样的图像

c# - Azure 模拟器使用 MVC 应用程序时速度缓慢,可能需要 120 秒才能注册点击或 JSON 调用

azure - 什么时候不应该使用 ACS?

git - aspnet core项目gitignore的常见做法是什么

c# - 穷人的 C# "lexer"

c# - SQL Server 存储过程无法识别 string.empty 等

c# - 使用 WinRT 接受无效的 SSL 证书

Azure Fabric SDK webapi 无法访问

asp.net-core - Dotnet 测试任务失败, '' MSB1008 : Only one project can be specified"error after upgrade to version 2. 0

c# - 如何在 Identity ASP.NET Core 2.1(Identity Scaffolded)中播种用户角色