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

asp.net core how to add claims to User

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

var currentUser = User;

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

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

is this how I should be getting my claims?

AFAIK,您可以利用 ControllerBase.HttpContext.UserControllerBase.User 来检索当前用户的 System.Security.Claims.ClaimsPrincipal。您可以按照类似 and .

的详细信息

And my second question is, how do I add claims to this User?

正如您所说,您使用的是 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