带有Adal版本2 Nuget包的Azure Web AD图API [英] Azure web AD graph api with adal version 2 nuget package

查看:85
本文介绍了带有Adal版本2 Nuget包的Azure Web AD图API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用azure AD图形API提取azure广告用户信息. graph API是否可以与adal 2 nuget包一起使用?

I am trying to pull azure ad user info using azure AD graph api. Will graph api work with adal 2 nuget packages?

这个问题的原因是 我的网络应用程序正在使用下面的代码进行身份验证,并且仅与使用Microsoft.IdentityModel.Clients.ActiveDirectory的Adal2x版本一起使用.

Reason for this question is My webapplication is using below code in for auth and works only with Adal2x versions using Microsoft.IdentityModel.Clients.ActiveDirectory.

但是Azure广告图使用不同的方式提取令牌,并且仅与adal3一起使用.AcquireTokenSilentAsync是adal3的一部分. AcquireTokenByAuthorizationCode是adal2的一部分,用于启动时进行身份验证.我必须同时使用身份验证和图形API.是否可以使用adal2x版本的用户图形api来匹配两者?

But Azure ad graph uses different way to pull token and it works only with adal3 .AcquireTokenSilentAsync is part of adal3. AcquireTokenByAuthorizationCode is part of adal2 for authentication on startup. I have to use both authentication and graph api. Is there any option to user graph api with adal2x version to match both?

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

推荐答案

基于测试,在2.28.3版本中退出了AcquireTokenSilentAsync方法.并且在最新版本的ADAL(3.13.8)中,该方法支持异步.我们可以使用AcquireTokenByAuthorizationCodeAsync代替AcquireTokenByAuthorizationCode.要使用此方法,您还可以参考代码示例

Based on the test, the AcquireTokenSilentAsync method is exited in version 2.28.3. And in the latest version of ADAL(3.13.8), the method is support asynchronous. We can use AcquireTokenByAuthorizationCodeAsync instead of AcquireTokenByAuthorizationCode. To use this method, you can also refer the code sample active-directory-dotnet-webapp-webapi-openidconnect.

但是Azure广告图使用不同的方式提取令牌,并且仅与adal3一起使用.AcquireTokenSilentAsync是adal3的一部分. AcquireTokenByAuthorizationCode是adal2的一部分,用于启动时进行身份验证.我必须同时使用身份验证和图形API.是否可以使用adal2x版本的用户图形api来匹配两者?

But Azure ad graph uses different way to pull token and it works only with adal3 .AcquireTokenSilentAsync is part of adal3. AcquireTokenByAuthorizationCode is part of adal2 for authentication on startup. I have to use both authentication and graph api. Is there any option to user graph api with adal2x version to match both?

Azure AD Graph用于读取和修改租户中的对象,例如用户,组和联系人.我们如何获得令牌以使用此REST API尚无定论.

Azure AD Graph is used to read and modify objects such as users, groups, and contacts in a tenant. It doesn't matther how we accquire the token to use this REST API.

Active Directory身份验证库可帮助获取来自Azure AD的令牌,但差异版本具有某些差异.有关ADAL发行版本的更多详细信息,可以在此处进行参考. >.

And the Active Directory Authentication Library is helped to acquire the token from Azure AD, but the difference version has some difference. More details about the release version of ADAL, you can refer here.

在您的方案中,ADAL的V2.0和V3.0版本都应该起作用.我建议您使用最新版本,因为它修复了旧版本中的几个错误.

In your scenario, both V2.0 and V3.0 version of ADAL should work. I suggest that you use the latest version since it fixed the several bugs in the old version.

这篇关于带有Adal版本2 Nuget包的Azure Web AD图API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆