带有 adal 版本 2 nuget 包的 Azure web AD 图 api
Azure web AD graph api with adal version 2 nuget package
我正在尝试使用 azure AD graph api 提取 azure 广告用户信息。图 api 可以与 adal 2 nuget 包一起使用吗?
这个问题的原因是
我的网络应用程序使用以下代码进行身份验证,并且仅适用于使用 Microsoft.IdentityModel.Clients.ActiveDirectory 的 Adal2x 版本。
但 Azure 广告图使用不同的方式来提取令牌,并且它仅适用于 adal3。AcquireTokenSilentAsync 是 adal3 的一部分。 AcquireTokenByAuthorizationCode 是 adal2 的一部分,用于在启动时进行身份验证。我必须同时使用身份验证和图形 api。用户图 api 和 adal2x 版本是否有任何选项可以匹配两者?
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);
}
经测试,AcquireTokenSilentAsync
方法在2.28.3
版本退出。并且在最新版本的 ADAL(3.13.8
) 中,该方法支持异步。我们可以使用 AcquireTokenByAuthorizationCodeAsync
而不是 AcquireTokenByAuthorizationCode
。要使用此方法,您还可以参考代码示例 active-directory-dotnet-webapp-webapi-openidconnect.
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.
还有 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.
在您的场景中,V2.0 和 V3.0 版本的 ADAL 都应该可以工作。我建议你使用最新版本,因为它修复了旧版本中的几个错误。
我正在尝试使用 azure AD graph api 提取 azure 广告用户信息。图 api 可以与 adal 2 nuget 包一起使用吗?
这个问题的原因是 我的网络应用程序使用以下代码进行身份验证,并且仅适用于使用 Microsoft.IdentityModel.Clients.ActiveDirectory 的 Adal2x 版本。
但 Azure 广告图使用不同的方式来提取令牌,并且它仅适用于 adal3。AcquireTokenSilentAsync 是 adal3 的一部分。 AcquireTokenByAuthorizationCode 是 adal2 的一部分,用于在启动时进行身份验证。我必须同时使用身份验证和图形 api。用户图 api 和 adal2x 版本是否有任何选项可以匹配两者?
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);
}
经测试,AcquireTokenSilentAsync
方法在2.28.3
版本退出。并且在最新版本的 ADAL(3.13.8
) 中,该方法支持异步。我们可以使用 AcquireTokenByAuthorizationCodeAsync
而不是 AcquireTokenByAuthorizationCode
。要使用此方法,您还可以参考代码示例 active-directory-dotnet-webapp-webapi-openidconnect.
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.
还有 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.
在您的场景中,V2.0 和 V3.0 版本的 ADAL 都应该可以工作。我建议你使用最新版本,因为它修复了旧版本中的几个错误。