使用 azure AzureADB2C 进行身份验证时,我想将在门户中管理的自定义声明添加到声明原则
current code in start up
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
我认为它应该像这样工作,但是在 token 验证上永远不会被命中
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options))
.AddJwtBearer(o =>
{
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
var claims = new List<Claim> { new Claim("ConfidentialAccess", "true") };
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
};
});
最佳答案
一般情况下,我们会使用 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通过安装包Microsoft.AspNetCore.Authentication.AzureADB2C.UI ,我假设你没有办法设置 OpenIdConnectEvents.OnTokenValidated .
来自AzureAdB2CAuthenticationBuilderExtensions.cs ,您可以在 AddAzureADB2C
方法下找到用于实例化 OpenIdConnectOptions
的代码行。
builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();
对于OpenIdConnectOptionsConfiguration.cs ,您可能会发现您没有机会设置OpenIdConnectOptions.Events
。
幸运的是,这里有一个代码示例,它单独定义了 AzureAdB2COptions.cs和 OpenIdConnectOptionsSetup.cs 。我假设您可以按照我的代码片段修改 OpenIdConnectOptionsSetup.cs 下的 Configure
方法。以满足您的要求。详细教程可以关注An ASP.NET Core web app with Azure AD B2C .
关于c# - 在 MVC Core 应用程序中使用 AddAzureADB2C 时向 ClaimsPrincipal 添加自定义声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965665/