【问题标题】:Add claims in Microsoft Identity WebApp Authentication在 Microsoft Identity WebApp 身份验证中添加声明
【发布时间】:2021-01-11 04:27:01
【问题描述】:

我正在尝试使用 azure-samples 专门从我的 asp.net core 3.1 mvc 应用程序登录用户。该示例可用并记录在here

但是,我找不到添加/修改在令牌中收到的声明的方法。使用的扩展方法是AddMicrosoftIdentityWebAppAuthentication() from Microsoft.Identity.Web nuget package version 0.4.0-preview

【问题讨论】:

    标签: asp.net-core azure-active-directory openid-connect


    【解决方案1】:

    使用以下代码向ClaimsPrincipal 添加新的角色声明:

    public ActionResult AddClaim()
    {
        Claim displayName = ClaimsPrincipal.Current.FindFirst(ClaimsPrincipal.Current.Identities.First().NameClaimType);
        ViewBag.DisplayName = displayName != null ? displayName.Value : string.Empty;
    
        //ClaimType, Value, ValueType, Issuer
        Claim localClaim = new Claim(ClaimTypes.Webpage, "http://localhost", ClaimValueTypes.String, "AADGuide");
        
        //Method 1 - short version
        ClaimsPrincipal.Current.Identities.First().AddClaim(localClaim);
        
        //Method 2 - slightly longer version
        //var user = User as ClaimsPrincipal;
        //var identity = user.Identity as ClaimsIdentity;
        //identity.AddClaim(localClaim);    
        
        return View();
    }
    

    此外,您可以使用 IUserClaimsPrincipalFactory 向 Identity 添加声明。

    【讨论】:

    • 您希望我在哪里添加此代码并从哪里调用它?这就是我在 Startup.cs 类中所拥有的 services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAD");
    • 如文章所说,putting the claims in ClaimsPrincipal.Current。因此,您可以在 startup.cs 文件中使用ClaimsPrincipal.Current.Identities.First().AddClaim(localClaim); 来添加声明。
    • 对不起,我这么无知,但我没有关注你。这是我在 Startup.cs 中的内容:public void ConfigureServices(IServiceCollection services){ services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAD") .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) .AddMicrosoftGraph(Configuration.GetSection("MSGraphApi")) .AddInMemoryTokenCaches(); } services.Configure<MicrosoftIdentityOptions>(options =>{options.Events.OnTokenValidated = async (context) => { // how to call call Graph to get AD groups and store them as claims? }}
    • 你好@Sam 你还在为这个问题寻求帮助吗?
    • 我按照here 的说明实现了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2020-04-21
    • 2022-01-20
    • 2018-07-04
    • 2016-04-23
    • 2012-07-03
    • 2011-12-25
    相关资源
    最近更新 更多