C# 向AspNetCore Azure认证应用程序添加自定义声明

C# 向AspNetCore Azure认证应用程序添加自定义声明,c#,asp.net-core,azure-active-directory,C#,Asp.net Core,Azure Active Directory,我将AspNetCore模板授权用于以下代码行: services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options)); 在用户获得Azure授权后,如何添加自定义声明?您可以在OIDC事件的OnTokenValidated中添加自定义Cliam: services.

我将AspNetCore模板授权用于以下代码行:

       services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

在用户获得Azure授权后,如何添加自定义声明?

您可以在OIDC事件的
OnTokenValidated
中添加自定义Cliam:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {


            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

您可以在OIDC事件的
OnTokenValidated
中添加自定义cliam:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {


            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

南宇。你知道我如何将我的DbContext传递给这里的声明吗?我知道了。必须添加以下内容:var db=ctx.HttpContext.RequestServices.GetRequiredService();南宇。你知道我如何将我的DbContext传递给这里的声明吗?我知道了。必须添加以下内容:var db=ctx.HttpContext.RequestServices.GetRequiredService();