asp.net核心如何向User添加声明

时间:2017-11-16 09:39:18

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

我使用的是带有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添加声明?

1 个答案:

答案 0 :(得分:7)

  

这是我应该如何得到我的主张?

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

<强>测试

enter image description here

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