Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core how to add claims to User

I am using ASP.NET Core 2.0, with Azure AD v2.0 endpoint. I am getting claims like this:

var currentUser = User;

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

I am not used to using this User to get claims, but could not get the old way with System.Security.Claims to work. So my first question is, is this how I should be getting my claims? And my second question is, how do I add claims to this User?

like image 921
Green_qaue Avatar asked Dec 08 '22 16:12

Green_qaue


1 Answers

is this how I should be getting my claims?

AFAIK, you could leverage ControllerBase.HttpContext.User or ControllerBase.User for retrieving the System.Security.Claims.ClaimsPrincipal for current user. Details you could follow the similar issue1 and issue2.

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

As you said you are using ASP.NET Core 2.0, with Azure AD v2.0. I assumed that when using UseOpenIdConnectAuthentication, you could add the additional claims under OnTokenValidated as follows:

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

Then, I used the following code to retrieve the user claims:

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

Test:

enter image description here

Moreover, you could refer to this sample Integrating Azure AD (v2.0 endpoint) into an ASP.NET Core web app.

like image 150
Bruce Chen Avatar answered Dec 10 '22 05:12

Bruce Chen