一般来说,我们会使用 OpenIdConnect 中间件进行 AAD 身份验证。您可以使用以下代码行添加自定义声明。
//OpenIdConnectOptions
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = context =>
{
var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
//add your custom claims here
claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));
return Task.FromResult(0);
}
};
如果您正在使用AzureADB2CAuthenticationBuilderExtensions.AddAzureADB2C https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.azureadb2cauthenticationbuilderextensions.addazureadb2c?view=aspnetcore-2.1通过安装包Microsoft.AspNetCore.Authentication.AzureADB2C.UI https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.AzureADB2C.UI,我假设你没有办法设置OpenIdConnectEvents.OnTokenValidated https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.openidconnect.openidconnectevents.ontokenvalidated?view=aspnetcore-2.1.
From AzureAdB2CAuthenticationBuilderExtensions.cs https://github.com/aspnet/AADIntegration/blob/28e81276582af23f4c616d9db900664960682074/src/Microsoft.AspNetCore.Authentication.AzureADB2C.UI/AzureAdB2CAuthenticationBuilderExtensions.cs,你可以在下面找到代码行AddAzureADB2C
实例化方法OpenIdConnectOptions
.
builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();
For OpenIdConnectOptions Configuration.cs https://github.com/aspnet/AADIntegration/blob/28e81276582af23f4c616d9db900664960682074/src/Microsoft.AspNetCore.Authentication.AzureAD.UI/OpenIdConnectOptionsConfiguration.cs,你会发现你没有机会设置OpenIdConnectOptions.Events
.
幸运的是,这里有一个代码示例,它单独定义了AzureAdB2COptions.cs https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp/blob/master/WebApp-OpenIDConnect-DotNet/AzureAdB2COptions.cs and OpenIdConnectOptionsSetup.cs https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp/blob/master/WebApp-OpenIDConnect-DotNet/OpenIdConnectOptionsSetup.cs。我假设你可以按照我的代码片段来修改Configure
下的方法OpenIdConnectOptionsSetup.cs https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp/blob/master/WebApp-OpenIDConnect-DotNet/OpenIdConnectOptionsSetup.cs以满足您的要求。详细教程你可以参考使用 Azure AD B2C 的 ASP.NET Core Web 应用 https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp.