Welcome to today’s post.
I will be discussing the creation and maintenance of user claims for user accounts using the ASP.NET Core Identity framework.
In a previous post I showed how to extend the user identity within a ASP.NET Core Identity application.
If you are already familiar with ASP.NET Core Identity and how to scaffold an identity implementation into your own ASP.NET MVC application or implemented custom identity based security authentication, then this discussion will be an extension on how you can implement claims into your application.
The motivation behind adding claims into your user accounts is to implement claims-based authorization into your applications, which can be used to implement more secure token-based security, such as JWT or OAuth2.
Before you can use the security claims API, declare the following namespace at the top of your source file:
using System.Security.Claims;
The most common function that is used to add new claims is when registering an new user account during user registration.
In the code below in a registration controller, we are adding claims as a list for user properties.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser {
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
DOB = model.DOB
};
var result = await _userManager.CreateAsync(user,
model.Password);
if (result.Succeeded)
{
_logger.LogInformation(
"User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(
user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(
model.Email, callbackUrl);
await _signInManager.SignInAsync(user,
isPersistent: false);
_logger.LogInformation("User created a new account with password.");
// add additional claims for this new user..
var newClaims = new List<Claim>() {
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.DateOfBirth,
user.DOB.ToShortDateString())
};
await _userManager.AddClaimsAsync(user, newClaims);
_logger.LogInformation("Claims added for user.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If execution got this far, something failed, redisplay the form.
return View(model);
}
We added the claims by creating an array of claims, then calling the user manager class with the array of claims.
await _userManager.AddClaimsAsync(user, newClaims);
After running the user registration in the user registration, the [AspNetUserClaims] table will be populated with the the claims data for the user.

When user account details are updated, user account properties that are also claims can also be updated, as shown in the code below in our manage controller.
We would first check if the user properties have changed, and if so update them accordingly:
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = user.Email;
if (model.Email != email)
{
var setEmailResult = await _userManager.SetEmailAsync(
user, model.Email);
if (!setEmailResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
}
}
var phoneNumber = user.PhoneNumber;
if (model.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
}
}
Next, we verify which of our claims properties has been updated:
// Flags for updated claims fields.
bool bHasFNUpdated = false;
bool bHasSNUpdated = false;
bool bHasDOBUpdated = false;
// custom field updates
if (model.FirstName != user.FirstName)
{
user.FirstName = model.FirstName;
bHasFNUpdated = true;
}
if (model.LastName != user.LastName)
{
user.LastName = model.LastName;
bHasSNUpdated = true;
}
if (model.DOB != user.DOB)
{
user.DOB = model.DOB;
bHasDOBUpdated = true;
}
Next, we determine which claims are existing in the user’s claims, and then assign these claims to a Claim object:
// add/update claims
bool bHasFNClaim = false;
bool bHasSNClaim = false;
bool bHasDOBClaim = false;
dynamic existingFNClaim = "";
dynamic existingSNClaim = "";
dynamic existingDOBClaim = "";
// check existing claims for user..
var userClaims = await _userManager.GetClaimsAsync(user);
foreach (Claim claim in userClaims)
{
if (claim.Type == ClaimTypes.GivenName)
{
bHasFNClaim = true;
existingFNClaim = (Claim)claim;
}
if (claim.Type == ClaimTypes.Surname)
{
bHasSNClaim = true;
existingSNClaim = (Claim)claim;
}
if (claim.Type == ClaimTypes.DateOfBirth)
{
bHasDOBClaim = true;
existingDOBClaim = (Claim)claim;
}
}
Next, we update the claims for the user to the data store. Where a claim already exists in our claims record, the current one is removed before the new claim is added:
var newFNClaim = new Claim(
ClaimTypes.GivenName,
user.FirstName
);
var newSNClaim = new Claim(
ClaimTypes.Surname,
user.LastName
);
var newDOBClaim = new Claim(
ClaimTypes.DateOfBirth,
user.DOB.ToShortDateString()
);
// add/update claims for user..
if (!bHasFNClaim)
{
await _userManager.AddClaimAsync(user, newFNClaim);
}
else if (bHasFNUpdated)
{
if (existingFNClaim.GetType().ToString() ==
"System.Security.Claims.Claim")
{
await _userManager.RemoveClaimAsync(user, existingFNClaim);
await _userManager.AddClaimAsync(user, newFNClaim);
}
}
if (!bHasSNClaim)
{
await _userManager.AddClaimAsync(user, newSNClaim);
}
else if (bHasSNUpdated)
{
if (existingSNClaim.GetType().ToString() ==
"System.Security.Claims.Claim")
{
await _userManager.RemoveClaimAsync(user, existingSNClaim);
await _userManager.AddClaimAsync(user, newSNClaim);
}
}
if (!bHasDOBClaim)
{
await _userManager.AddClaimAsync(user, newDOBClaim);
}
else if (bHasDOBUpdated)
{
if (existingDOBClaim.GetType().ToString() ==
"System.Security.Claims.Claim")
{
await _userManager.RemoveClaimAsync(user, existingDOBClaim);
await _userManager.AddClaimAsync(user, newDOBClaim);
}
}
_logger.LogInformation("Claims added/updated for user.");
await _userManager.UpdateAsync(user);
StatusMessage = "Your profile has been updated";
Essentially what we are doing in the updating of claims is:
- Check existing claims for the user.
- If the modified user properties that are claims are updated, then remove their respective claims (from 1) and add new claims with the modified properties.
- If there are no existing claims for the modified user properties, then add new claims with the modified properties.
That’s all for this post.
I hope you have found this post useful and learned something useful.

Andrew Halil is a blogger, author and software developer with expertise of many areas in the information technology industry including full-stack web and native cloud based development, test driven development and Devops.