liveBook · Manning

ClaimsPrincipal

As explained in ASP.NET Core in Action, 3e

ClaimsPrincipal is a .NET security object that represents an authenticated user through a collection of claims and identities.

ClaimsPrincipal represents the current user of an ASP.NET Core request. It is available through HttpContext.User and carries claims: individual pieces of information about the user, such as a name, email address, or permission-related value. A claim has a type and an optional value. section 23.1.1 section 23.7

Every request starts with an anonymous, unauthenticated principal with no claims. After a successful sign-in, authentication services set the principal and can save it in an encrypted cookie. On a later request, the cookie is validated and used to authenticate the request. section 23.1.1 section 23.1.2

In a minimal API handler, you can request a ClaimsPrincipal parameter directly instead of injecting HttpContext and navigating to its User property. In Razor Pages and views, User provides access to the current principal and its claims. section 7.6.1 section 23.7

A ClaimsPrincipal is not the same as an IdentityUser stored in the database. At login, Identity combines the user entity with additional stored claims to create the principal. The principal, not the IdentityUser, is serialized to the authentication cookie. section 23.3.3

Add and read a name claim

To collect a friendly name at registration, add a Name field to the registration input, then create a FullName claim after the user is created and add it with UserManager.AddClaimAsync. The claim can then be read from User in a Razor page or template. section 23.6

Listing 23.7 Adding a custom claim to a new user in the Register.cshtml.cs page
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser {                        #1
            UserName = Input.Email, Email = Input.Email };      #1
        var result = await _userManager.CreateAsync(            #2
            user, Input.Password);                              #2
        if (result.Succeeded)
        {
            var claim = new Claim("FullName", Input.Name);      #3
            await _userManager.AddClaimAsync(user, claim);      #4
            var code = await _userManager                       #5
                .GenerateEmailConfirmationTokenAsync(user);     #5
            await _emailSender.SendEmailAsync(                  #5
                 Input.Email, "Confirm your email", code );     #5
            await _signInManager.SignInAsync(user);             #6
            return LocalRedirect(returnUrl);
        }
        foreach (var error in result.Errors)                    #7
        {                                                       #7
            ModelState.AddModelError(                           #7
                string.Empty, error.Description);               #7
        }                                                       #7
    }                                                           #7
       return Page();                                           #7
}
#1 Creates an instance of the ApplicationUser entity
#2 Validates that the provided password meets requirements, and creates the user in the database
#3 Creates a claim, with a string name of “FullName” and the provided value
#4 Adds the new claim to the ApplicationUser’s collection
#5 Sends a confirmation email to the user, if you have configured the email sender
#6 Signs the user in by setting the HttpContext.User; the principal will include the custom claim
#7 There was a problem creating the user. Adds the errors to the ModelState and redisplays the page.

The registration handler creates the user before adding the FullName claim. section 23.6

@User.FindFirstValue("FullName")

FindFirstValue retrieves the FullName claim value from the current principal. section 23.6

Claims can also represent permissions, such as IsAdmin. Such claims may be added to selected users after registration rather than granted to everyone. For new apps, prefer the claims-based approach; role-based security remains compatible for legacy use. section 23.6 section 23.1.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains claims, request access, cookie authentication, and Identity-backed customization through a registration example.
Examples
Uses a FullName claim added during registration and read from a Razor page.
What you can do after
Apply it via ASP.NET Core Identity to add user claims and retrieve their values in Razor.
How it connects
Connects claims to authentication, authorization, cookies, and ASP.NET Core Identity.

Also explained in

Compare how 2 books explain ClaimsPrincipal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.