2017-06-02 96 views
1

讓我首先說這是我的第一個.net核心應用程序,因此我可能會在這裏以一個白癡的身份出現。一般來說,我也是新的代幣。從asp.net核心獲取Microsoft Graph的訪問令牌認證Web應用程序

這麼說,我有一個應用程序,它驗證對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")]

所有這些都是工作g reat,所以我的問題是我已經擁有的cookie是否包含我需要的令牌,如果是這樣,我可以簡單地使用User.Claims來訪問它,還是需要使用IAuthenticationProvider來設置它的示例。 net 4.6 Here

如果是後者,我如何在沒有使用Owin的情況下如此操作?

我應該補充說,雖然授權工作正常,但現在我想要做的事情包括像列出OU中的所有用戶這樣的事情。據我所知,我必須訪問Microsoft Graph。也許,我正在走向完全錯誤的方向?

+0

相關:https://stackoverflow.com/questions/41519132/how-to-store-the-token-received-in-acquiretokenasync-with-active-directory –

回答

3

您可以使用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身份驗證處理程序實際上可以爲您檢索令牌。

+0

謝謝!我發誓,我到處搜尋,正是因爲這一點。大聲笑。我沒有使用大量的軟件包,所以如果我的支持沒有太多的額外工作,我會跳到2.0。 –

+0

2.0仍然處於預覽狀態,因此您可以獲得出血邊緣的所有問題:) – juunas

相關問題