2017-03-07 37 views
0

我想拉蔚藍廣告用戶信息使用天藍AD圖形api。圖表API可以與adal 2 nuget軟件包一起使用嗎?Azure網絡AD圖形API與adal版本2 nuget包

此問題的原因是 我的web應用程序正在使用以下代碼進行身份驗證,並且僅與使用Microsoft.IdentityModel.Clients.ActiveDirectory的Adal2x版本一起使用。

但Azure廣告圖形使用不同的方式拉取令牌,並且它僅適用於adal3 .AcquireTokenSilentAsync是adal3的一部分。 AcquireTokenByAuthorizationCode是啓動時用於身份驗證的adal2的一部分。我必須同時使用身份驗證和圖形API。是否有任何選項與adal2x版本的用戶圖形api匹配?

public void ConfigureAuth(IAppBuilder app) 
     { 
      ApplicationDbContext db = new ApplicationDbContext(); 

      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 

      app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

      app.UseOpenIdConnectAuthentication(
       new OpenIdConnectAuthenticationOptions 
       { 
        ClientId = clientId, 
        Authority = Authority, 
        PostLogoutRedirectUri = postLogoutRedirectUri, 

        Notifications = new OpenIdConnectAuthenticationNotifications() 
        { 
         //If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. 
         AuthorizationCodeReceived = (context) => 
         { 
          var code = context.Code; 
          ClientCredential credential = new ClientCredential(clientId, appKey); 
          string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 
          AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID)); 
          //AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
          //code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); 
          AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
          code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); 
          return Task.FromResult(0); 
         } 
        } 
       }); 
     } 

圖形API代碼

public async Task<ActionResult> Index() 
     { 
      UserProfile profile; 
      string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; 
      AuthenticationResult result = null; 

      try 
      { 
       // Get the access token from the cache 
       string userObjectID = 
        ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier") 
         .Value; 
       AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, 
        new NaiveSessionCache(userObjectID)); 
       ClientCredential credential = new ClientCredential(clientId, appKey); 

       result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, 
        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); 

       // Call the Graph API manually and retrieve the user's profile. 
       string requestUrl = String.Format(
        CultureInfo.InvariantCulture, 
        graphUserUrl, 
        HttpUtility.UrlEncode(tenantId)); 
       HttpClient client = new HttpClient(); 
       HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); 
       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 
       HttpResponseMessage response = await client.SendAsync(request); 

       // Return the user's profile in the view. 
       if (response.IsSuccessStatusCode) 
       { 
        string responseString = await response.Content.ReadAsStringAsync(); 
        profile = JsonConvert.DeserializeObject<UserProfile>(responseString); 
       } 
       else 
       { 
        // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again. 
        authContext.TokenCache.Clear(); 

        profile = new UserProfile(); 
        profile.DisplayName = " "; 
        profile.GivenName = " "; 
        profile.Surname = " "; 
        ViewBag.ErrorMessage = "UnexpectedError"; 
       } 
      } 
      catch (Exception e) 
      { 
       if (Request.QueryString["reauth"] == "True") 
       { 
        // 
        // Send an OpenID Connect sign-in request to get a new set of tokens. 
        // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. 
        // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. 
        // 
        HttpContext.GetOwinContext() 
         .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); 
       } 

       // 
       // The user needs to re-authorize. Show them a message to that effect. 
       // 
       profile = new UserProfile(); 
       profile.DisplayName = " "; 
       profile.GivenName = " "; 
       profile.Surname = " "; 
       ViewBag.ErrorMessage = "AuthorizationRequired"; 
      } 

      return View(profile); 
     } 
+0

此問題的任何更新? –

回答

1

基於該測試中,AcquireTokenSilentAsync方法在2.28.3版本退出。並且在最新版本的ADAL(3.13.8)中,該方法支持異步。我們可以使用AcquireTokenByAuthorizationCodeAsync而不是AcquireTokenByAuthorizationCode。要使用此方法,還可以參考代碼示例active-directory-dotnet-webapp-webapi-openidconnect

但Azure廣告圖形使用不同的方式拉取令牌,並且它僅適用於adal3 .AcquireTokenSilentAsync是adal3的一部分。 AcquireTokenByAuthorizationCode是啓動時用於身份驗證的adal2的一部分。我必須同時使用身份驗證和圖形API。是否有任何選項與adal2x版本的用戶圖形api匹配?

Azure AD Graph用於讀取和修改租戶中的用戶,組和聯繫人等對象。它並不關心我們如何獲得令牌以使用此REST API。

Active Directory Authentication Library有助於從Azure AD獲取令牌,但差異版本有一些差異。有關ADAL發佈版本的更多細節,可以參考here

在您的場景中,ADAL的V2.0和V3.0版本都應該可以工作。我建議你使用最新版本,因爲它修復了舊版本中的幾個錯誤。

+0

謝謝我瞭解背景。用這裏的代碼生成的令牌是否可以與graphapi一起使用? http://stackoverflow.com/questions/42662234/azure-ad-graph-api-not-pulling-user-information – Kurkula

+1

我已經回答了這個問題,請隨時讓我知道,如果你仍然有問題。 –

+0

使用此令牌,我可以使用圖形api獲取azure活動目錄組名稱嗎?我是否需要任何特定的權限才能訪問羣組名稱?我是一個天藍色的門戶貢獻者。 – Kurkula