【发布时间】:2017-12-07 22:48:07
【问题描述】:
我正在尝试在一个身份服务器中启用多个 AzureAD 的登录功能。
这是必要的,因为多个租户需要能够通过 1 个身份服务器登录到他们自己的 AzureAD。这些设置将动态进行。
对于这个例子,我对 AuthenticationBuilder 做了一个扩展,它允许传递多个 AzureAd 并将它们添加到 AuthenticationBuilder。
//startup.cs
Dictionary<string, string> azure1 = new Dictionary<string, string>();
azure1.Add("name", "azure1");
azure1.Add("clientid", <azure1id>);
azure1.Add("tenantid", <azure1tenant>);
Dictionary<string, string> azure2 = new Dictionary<string, string>();
azure2.Add("name", "azure2");
azure2.Add("clientid", <azure2id>);
azure2.Add("tenantid", <azure2tenant>);
Dictionary<string, string>[] ids = { azure1, azure2 };
services.AddAuthentication()
.AddCookie()
.AddAzureAdAuthentications(ids)
//AuthenticationBuilderExtension
public static AuthenticationBuilder AddAzureAdAuthentications(this AuthenticationBuilder builder, Dictionary<string, string>[] azureAds)
{
string name = "";
string clientid = "";
string tenantid = "";
foreach (Dictionary<string, string> azuread in azureAds)
{
name = azuread.GetValueOrDefault("name");
clientid = azuread.GetValueOrDefault("clientid");
tenantid = azuread.GetValueOrDefault("tenantid");
builder.AddOpenIdConnect(name, name, options =>
{
options.Authority = $"https://login.microsoftonline.com/{tenantid}";
options.ClientId = clientid;
options.ResponseType = OpenIdConnectResponseType.IdToken;
});
}
return builder;
}
我希望上面的代码添加 2 个 azureAd 作为登录选项,这很好用。我认为身份验证流程会保持不变。
相反,出现了 2 个问题。
- 两个登录选项都导致最后一个配置 (azure2),azure1 就消失了。这意味着最后一个配置将覆盖第一个配置。
- 使用有效账号登录azure2时,登录identityserver失败,出现如下错误:
异常:关联失败。 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()
从字典中删除 2 个 AzureAD 中的 1 个会导致一切正常。
更新
实施 minimumprivileges 答案(谢谢)导致以下结果: 它“几乎”有效。 AzureAD 被正确识别,导致正确的流程并仅接受相应的帐户。但是现在客户端回调到identityserver后并没有成功登录。
我觉得这只是关于签到方案的一个小修改,但我无法真正弄清楚,因为这方面的文档非常少。
foreach (Dictionary<string, string> azuread in ids)
{
string name = azuread.GetValueOrDefault("name");
string clientid = azuread.GetValueOrDefault("clientid");
string tenantid = azuread.GetValueOrDefault("tenantid");
services.AddAuthentication(name).AddCookie($"Cookie{name}").AddOpenIdConnect(name, name, options =>
{
options.SignInScheme = $"Cookie{name}";
options.SignOutScheme = $"Cookie1{name}";
options.CallbackPath = $"/signin-{name}";
options.Authority = $"https://login.microsoftonline.com/{tenantid}";
options.ClientId = clientid;
options.ResponseType = OpenIdConnectResponseType.IdToken;
});
}
解决方案
可能并不难,但分享解决方案以帮助他人:
services.AddAuthentication().AddCookie($"Cookie{name}")
.AddOpenIdConnect(name, name, options =>
{
options.CallbackPath = $"/signin-{name}";
options.Authority = $"https://login.microsoftonline.com/{tenantid}";
options.ClientId = clientid;
options.ResponseType = OpenIdConnectResponseType.IdToken;
});
【问题讨论】:
标签: asp.net-core azure-active-directory identityserver4