簡體   English   中英

向 AspNetCore Azure 身份驗證應用程序添加自定義聲明

[英]Adding Custom Claims to AspNetCore Azure Authenticated Application

我在這行代碼中使用了 AspNetCore 模板授權:

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

用戶獲得 Azure 授權后,如何添加自定義聲明?

您可以添加自定義cliams OnTokenValidated OIDC事件:

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;
        },
    };
});

然后在控制器中,您可以獲得如下聲明:

var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM