【问题标题】:asp.net core how to add claims to Userasp.net核心如何向用户添加声明
【发布时间】:2017-11-16 09:39:18
【问题描述】:

我正在使用带有 Azure AD v2.0 端点的 ASP.NET Core 2.0。 我收到这样的声明:

var currentUser = User;

var displayName = currentUser.FindFirst("name").Value;
var claims = currentUser.Claims;

我不习惯使用 User 来获取索赔,但无法使用 System.Security.Claims 的旧方法来工作。所以我的第一个问题是,这是我应该如何获得索赔的方式吗?我的第二个问题是,如何向 User 添加声明?

【问题讨论】:

    标签: c# azure asp.net-core claims-based-identity


    【解决方案1】:

    这就是我应该得到我的索赔的方式吗?

    AFAIK,您可以利用ControllerBase.HttpContext.UserControllerBase.User 检索当前用户的System.Security.Claims.ClaimsPrincipal。详情可以关注issue1issue2

    我的第二个问题是,如何向该用户添加声明?

    正如您所说,您使用的是 ASP.NET Core 2.0 和 Azure AD v2.0。我假设在使用UseOpenIdConnectAuthentication 时,您可以在OnTokenValidated 下添加附加声明,如下所示:

    app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
    {
        ClientId = Configuration["AzureAD:ClientId"],
        Authority = string.Format(CultureInfo.InvariantCulture, Configuration["AzureAd:AadInstance"], "common", "/v2.0"),
        ResponseType = OpenIdConnectResponseType.IdToken,
        PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
        Events = new OpenIdConnectEvents
        {
            OnRemoteFailure = RemoteFailure,
            OnTokenValidated = TokenValidated
        },
        TokenValidationParameters = new TokenValidationParameters
        {
            // Instead of using the default validation (validating against
            // a single issuer value, as we do in line of business apps), 
            // we inject our own multitenant validation logic
            ValidateIssuer = false,
    
            NameClaimType = "name"
        }
    });
    
    private Task TokenValidated(TokenValidatedContext context)
    {
        /* ---------------------
        // Replace this with your logic to validate the issuer/tenant
            ---------------------       
        // Retriever caller data from the incoming principal
        string issuer = context.SecurityToken.Issuer;
        string subject = context.SecurityToken.Subject;
        string tenantID = context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
    
        // Build a dictionary of approved tenants
        IEnumerable<string> approvedTenantIds = new List<string>
        {
            "<Your tenantID>",
            "9188040d-6c67-4c5b-b112-36a304b66dad" // MSA Tenant
        };
        o
        if (!approvedTenantIds.Contains(tenantID))
            throw new SecurityTokenValidationException();
            --------------------- */
    
        var claimsIdentity=(ClaimsIdentity)context.Ticket.Principal.Identity;
        //add your custom claims here
        claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));
    
        return Task.FromResult(0);
    }
    

    然后,我使用以下代码检索用户声明:

    public IActionResult UserInfo()
    {
        return Json(User.Claims.Select(c=>new {type=c.Type,value=c.Value}).ToList());
    }
    

    测试:

    另外,您可以参考这个示例Integrating Azure AD (v2.0 endpoint) into an ASP.NET Core web app

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 2018-12-16
      • 2019-06-29
      • 2015-02-14
      • 1970-01-01
      • 2018-04-25
      相关资源
      最近更新 更多