2017-03-07 3 views
0

I azur ad Benutzer Info mit azur AD Graph api zu ziehen versuchen. Funktioniert die Graphik-API mit den nuget-Paketen von adal 2?Azure Web AD Graph api mit adal Version 2 nuget Paket

Grund für diese Frage ist Meine Webanwendung verwendet unterhalb Code für Auth und funktioniert nur mit Adal2x-Versionen mit Microsoft.IdentityModel.Clients.ActiveDirectory.

Aber Azure ad Graph verwendet unterschiedliche Art und Weise Token zu ziehen und es funktioniert nur mit adal3 .AcquireTokenSilentAsync Teil adal3 ist. AcquireTokenByAuthorizationCode ist Teil von adal2 für die Authentifizierung beim Start. Ich muss sowohl Authentifizierung als auch Graphik-API verwenden. Gibt es eine Option, graph api mit der adal2x-Version zu verwenden, um beide zu erreichen?

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

Graph api Code

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

Jedes Update für dieses Problem? –

Antwort

1

auf dem Test Basierend wird die AcquireTokenSilentAsync Methode in Version 2.28.3 verlassen. Und in der neuesten Version von ADAL (3.13.8) ist die Methode asynchrone Unterstützung. Wir können AcquireTokenByAuthorizationCodeAsync anstelle von AcquireTokenByAuthorizationCode verwenden. Um diese Methode zu verwenden, können Sie auch das Codebeispiel active-directory-dotnet-webapp-webapi-openidconnect verwenden.

Aber Azure Ad-Diagramm verwendet andere Möglichkeit, Token zu ziehen, und es funktioniert nur mit Adal3. AcquireTokenSilentAsync ist Teil von Adal3. AcquireTokenByAuthorizationCode ist Teil von adal2 für die Authentifizierung beim Start. Ich muss sowohl Authentifizierung als auch Graphik-API verwenden. Gibt es eine Option, graph api mit der adal2x-Version zu verwenden, um beide zu erreichen?

Azure AD Graph wird zum Lesen und Ändern von Objekten wie Benutzern, Gruppen und Kontakten in einem Mandanten verwendet. Es kommt nicht darauf an, wie wir das Token für die Verwendung dieser REST-API erwerben.

Und die Active Directory Authentication Library wird dazu beigetragen, die Token von Azure AD zu erwerben, aber der Unterschied Version einige Unterschiede aufweist. Weitere Details zur Release-Version von ADAL finden Sie unter here.

In Ihrem Szenario sowohl V2.0 und V3.0 Version von ADAL sollte funktionieren. Ich schlage vor, dass Sie die neueste Version verwenden, da es die verschiedenen Fehler in der alten Version behoben hat.

+0

Danke Ich habe den Hintergrund verstanden. Wird der mit dem Code von hier generierte Token mit graphapi funktionieren? http://stackoverflow.com/questions/42662234/azure-ad-graph-api-not-pulling-user-information – Kurkula

+1

Ich habe die Frage geantwortet, bitte zögern Sie nicht mich wissen zu lassen, wenn Sie immer noch das Problem haben. –

+0

mit diesem Token, kann ich Azure Active Directory-Gruppennamen mit Graph API erhalten? Benötige ich spezielle Berechtigungen für den Zugriff auf Gruppennamen? Ich bin ein azurblauer Portalmitwirkender. – Kurkula

Verwandte Themen