如何使OAuth2适用于具有.net上的多重身份验证的Azure Active Directory?



我们在Azure Active Directory上使用OAuth 2.0身份验证代码授权来验证Web应用程序中的用户。

这没有问题,但现在 AD 维护想要部署多重身份验证。我们目前的OAuth实现与此不符。

这是我们的代码:

public static ActionResult LogOn()
{
string authorizationUrl = string.Format(
"https://login.windows.net/{0}/oauth2/authorize?api-version=1.0&response_type=code&response_mode=query&client_id={1}&scope={2}&redirect_uri={3}",
HttpUtility.UrlEncode(azureActiveDirectoryTenant),
HttpUtility.UrlEncode(azureActiveDirectoryClientId),
HttpUtility.UrlEncode("https://graph.microsoft.com/v1.0/me/"),
HttpUtility.UrlEncode(azureActiveDirectoryCodeRedirectURL) // refers to Code() below
);
return new RedirectResult(authorizationUrl, false);
}
public async Task<ActionResult> Code(string code = null, string state = "", string error = null, string error_description = null)
{
if (String.IsNullOrEmpty(error))
{
if (String.IsNullOrWhiteSpace(code))
{
return LogOn();
}
AuthenticationContext ctx = new AuthenticationContext("https://login.microsoftonline.com/" + azureActiveDirectoryTenant);
ClientCredential clcred = new ClientCredential(azureActiveDirectoryClientId, azureActiveDirectoryClientKey);
try
{
var ar = await ctx.AcquireTokenByAuthorizationCodeAsync(code, new Uri(azureActiveDirectoryCodeRedirectURL), clcred, "https://graph.windows.net");
string email = ar.UserInfo.DisplayableId;
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer " + ar.AccessToken);
Stream data = client.OpenRead(new Uri("https://graph.windows.net/me?api-version=1.6"));
StreamReader reader = new StreamReader(data);
Dictionary<string, dynamic> values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(reader.ReadToEnd());
data.Close();
reader.Close();
... act on values and redirect...
}
}
catch (AdalServiceException ex)
{
// We come here!
ViewBag.ErrorMessage = String.Format("Exception: ErrorCode: {0}, StatusCode: {1}, Message: {2}.", ex.ErrorCode, ex.StatusCode, ex.Message);
...
}
}
return View("OAuthError");
}

和错误消息:

ErrorCode: interaction_required, StatusCode: 400, Message: AADSTS50076: Due
to a configuration change made by your administrator, or because you moved to a
new location, you must use multi-factor authentication to access '00000002-0000-
c000-0000000000000'.

本文档讨论 AAD 上的条件访问,并提到"声明"作为解决方案。

如何将声明合并到上面的代码中以使其工作?

每个Microsoft文档:https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/0fc398ca-88d0-4118-ae60-c3033e396e60

您可以将amr_values=ngcmfa添加到授权 URL 以强制 MFA。

您还可以添加amr_values=mfa以要求用户已通过 MFA,尽管它可能在一段时间前发生。

然后,还应检查令牌是否在 amr 声明中包含"mfa"。(因为用户可以删除参数(

相关内容

最新更新