我已将身份提供程序配置为使用具有用户名而不是密码的本地帐户.
我创建了一个具有显示名称,用户名和电子邮件的用户.
我可以为所有策略选择"显示名称"和"电子邮件地址"应用程序声明,但"用户名"不是一个选项.我还确认没有向我的应用程序提供用户名声明.
如何配置Azure AD B2C以便提供用户名声明?
不幸的是,用户名尚不可用于选择作为在令牌中传递的声明。您应该在 Azure AD B2C UserVoice 论坛中投票支持此问题以帮助确定优先级:在 JWT 声明中包含用户名
这次您唯一的选择是通过 Graph 自己检索它。
这是您可以用于此目的的 .Net 代码的快速而肮脏的片段:
private async Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
try
{
var userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
// You'll need to register a separate app for this.
// This app will need APPLICATION (not Delegated) Directory.Read permissions
// Check out this link for more info:
// https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format(graphAuthority, tenant));
var t = await authContext.AcquireTokenAsync(graphResource, new ClientCredential(graphClientId, graphClientSecret));
string result;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.AccessToken);
var url = graphResource + tenant + "/users/" + userObjectId + "/?api-version=1.6";
result = await client.GetStringAsync(url);
}
var jsonResult = JObject.Parse(result);
var username = jsonResult["signInNames"].FirstOrDefault(j => j["type"].ToString() == "userName")?["value"]?.ToString();
notification.AuthenticationTicket.Identity.AddClaim(new Claim("username", username));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
当您像这样设置 OpenIdConnectAuthenticationOptions 时,您将引用此方法:
new OpenIdConnectAuthenticationOptions
{
// (...)
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
SecurityTokenValidated = OnSecurityTokenValidated,
},
// (...)
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1498 次 |
| 最近记录: |