Introduction
Allowing a user to sign in is only the first step in building a secure authentication infrastructure. Real applications must also control what users can do, which data they can access, and what additional information is associated with their identity. ASP.NET Core Identity provides services for managing users, roles, claims, and the relationships between them.
In this lesson, we will use UserManager<TUser> and RoleManager<TRole> to create users and roles. We will assign and remove roles, add user-specific claims, and use those claims with policy-based authorization.
Identity manages many concerns, including users, passwords, profile data, roles, claims, and token providers. Roles usually represent broad groups of permissions, while claims carry more detailed information about a user or identity. Therefore, not every claim is a role, even though roles may also be represented as claims on an authenticated identity.
1. The relationship between users, roles and claims
User
An Identity user is commonly an IdentityUser or an application-specific class derived from it. Identity manages fields such as the username, email address, password hash, security stamp, and account lockout information.
Role
A role is a shared authorization group that can be assigned to multiple users. Typical examples include Admin, Editor, and Customer. An MVC controller or API endpoint can be restricted to administrators with [Authorize(Roles = "Admin")].
Claim
A claim is a name-value pair describing an identity. Examples include department=finance, tenant=contoso, or permission=reports.read. Claims support more precise authorization rules than a simple role check.
| Structure | Example | Typical use |
|---|---|---|
| User | ayse@example.com | Identity and account data |
| Role | Admin | Shared, broad permission group |
| Claim | department=finance | User-specific or fine-grained information |
2. Configuring Identity services
If the application will use role management, the Identity registration must include AddRoles<IdentityRole>(). The following example uses the ApplicationUser and ApplicationDbContext classes created in earlier lessons.
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("FinanceOnly", policy =>
policy.RequireClaim("department", "finance"));
});The middleware order is important:
app.UseAuthentication();
app.UseAuthorization();UseAuthorization depends on the authenticated user created by the authentication middleware in HttpContext.User. If role services are not registered, user operations may work while role-based checks do not behave as expected.
3. Creating roles
Roles are commonly seeded when the application starts. Use RoleExistsAsync before creating a role so that the same role is not inserted every time the application starts.
public static class IdentitySeeder
{
public static async Task SeedRolesAsync(
RoleManager<IdentityRole> roleManager)
{
string[] roles = ["Admin", "Editor", "Customer"];
foreach (var roleName in roles)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
var result = await roleManager.CreateAsync(
new IdentityRole(roleName));
if (!result.Succeeded)
{
var errors = string.Join(", ",
result.Errors.Select(e => e.Description));
throw new InvalidOperationException(
$"Role creation failed: {roleName}. {errors}");
}
}
}
}
}Call the seeding method from a startup scope:
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider
.GetRequiredService<RoleManager<IdentityRole>>();
await IdentitySeeder.SeedRolesAsync(roleManager);
}In production, make sure startup seeding cannot create unexpected administrator accounts on every deployment. Initial roles should be explicit, reviewed, and managed carefully.
4. Creating a user and assigning a role
Use UserManager<ApplicationUser> for user operations. Calling CreateAsync(user, password) allows Identity to apply its password hashing and validation mechanisms instead of writing a password directly to the database.
[ApiController]
[Route("api/admin/users")]
[Authorize(Roles = "Admin")]
public class UsersController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public UsersController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
[HttpPost]
public async Task<IActionResult> Create(CreateUserRequest request)
{
var user = new ApplicationUser
{
UserName = request.Email,
Email = request.Email
};
var createResult = await _userManager.CreateAsync(
user, request.Password);
if (!createResult.Succeeded)
return BadRequest(createResult.Errors);
if (!await _roleManager.RoleExistsAsync(request.Role))
return BadRequest("The specified role does not exist.");
var roleResult = await _userManager.AddToRoleAsync(
user, request.Role);
if (!roleResult.Succeeded)
return BadRequest(roleResult.Errors);
return Created($"api/admin/users/{user.Id}",
new { user.Id, user.Email, Role = request.Role });
}
}
public record CreateUserRequest(
string Email,
string Password,
string Role);In a real application, a role name supplied by a client should not be accepted without validation. Restrict roles to an allowlist and expose sensitive roles only through a dedicated administrative workflow.
5. Listing, adding, and removing roles
Use GetRolesAsync to read a user's roles, AddToRoleAsync to add a role, and RemoveFromRoleAsync to remove one.
var user = await _userManager.FindByIdAsync(userId);
if (user is null)
return NotFound();
var roles = await _userManager.GetRolesAsync(user);
var addResult = await _userManager.AddToRoleAsync(user, "Editor");
if (!addResult.Succeeded)
return BadRequest(addResult.Errors);
var removeResult = await _userManager.RemoveFromRoleAsync(user, "Customer");
if (!removeResult.Succeeded)
return BadRequest(removeResult.Errors);To remove all roles, use RemoveFromRolesAsync. However, application rules should prevent situations such as removing the final administrator and leaving the system without an account capable of managing access.
6. Adding user-specific claims
Add a single claim with AddClaimAsync, or multiple claims with AddClaimsAsync. The following example stores a user's department and report permission.
var claims = new[]
{
new Claim("department", "finance"),
new Claim("permission", "reports.read")
};
var result = await _userManager.AddClaimsAsync(user, claims);
if (!result.Succeeded)
return BadRequest(result.Errors);Claim types should be stable and documented within the application. For example, using department in one place and Department in another can cause authorization failures, especially when claim comparisons are case-sensitive.
Read the user's current claims as follows:
var userClaims = await _userManager.GetClaimsAsync(user);
var department = userClaims.FirstOrDefault(
c => c.Type == "department")?.Value;To update a claim, replacing the old value with a new one is usually clearer than adding duplicate values:
var oldClaim = userClaims.FirstOrDefault(
c => c.Type == "department");
if (oldClaim is not null)
await _userManager.ReplaceClaimAsync(
user, oldClaim, new Claim("department", "legal"));Claims that are no longer needed can be removed with RemoveClaimAsync.
7. Using claims for authorization
Persisting a claim does not automatically enforce access control. The claim must be evaluated by an authorization policy:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("FinanceOnly", policy =>
policy.RequireClaim("department", "finance"));
options.AddPolicy("CanReadReports", policy =>
policy.RequireClaim("permission", "reports.read"));
});Protect a controller action or endpoint with the policy:
[HttpGet("reports")]
[Authorize(Policy = "CanReadReports")]
public IActionResult Reports()
{
return Ok(new { Message = "Reports can be viewed." });
}Role and claim requirements can also be combined. For example, the following policy allows only users in the Admin role who also have department=finance:
options.AddPolicy("FinanceAdministrators", policy =>
{
policy.RequireRole("Admin");
policy.RequireClaim("department", "finance");
});A role answers “which group do you belong to?” A claim answers “which verified information describes this identity?” Do not treat the two concepts as interchangeable in your authorization design.
8. Refreshing identity during authentication
With cookie authentication, claims may be copied into the authentication cookie when the user signs in. If a role or claim changes later, the existing cookie may not change immediately. Refresh the sign-in session after the update by using SignInManager.RefreshSignInAsync.
await _userManager.AddClaimAsync(
user, new Claim("permission", "reports.read"));
await _signInManager.RefreshSignInAsync(user);The same principle applies to JWT authentication: changing a claim in the database does not modify an already-issued access token. A new token must be issued before the updated claims can appear in token-based authentication. JWT claim construction and validation will be covered in later lessons.
9. Common mistakes
- Forgetting AddRoles: Role-based authorization may not work correctly if role services are not registered.
- Ignoring IdentityResult: User, role, and claim operations can fail. Always inspect
result.Errors. - Trusting a client-provided claim: Never persist a claim from an untrusted request without validating it on the server.
- Putting every piece of data into claims: Large profile data in cookies or tokens can create size, privacy, and performance problems.
- Allowing arbitrary role names: An endpoint that lets a user assign themselves the
Adminrole creates a critical privilege-escalation vulnerability. - Not refreshing the session: The old cookie may continue to be used after a role or claim is changed.
- Using inconsistent claim types: Manage claim names and values with constants or a centralized vocabulary.
10. Practice exercise
Extend the Identity project from the previous lessons:
- Seed the
Admin,Editor, andCustomerroles. - Create a user-list endpoint accessible only to users in the
Adminrole. - Create an administrative endpoint that adds the
department=financeclaim to a user. - Register the
FinanceOnlypolicy and protect an endpoint with it. - Refresh the cookie session after adding the claim and test the endpoint again.
- Test the behavior with a non-admin user and observe the difference between
401and403.
Conclusion
This lesson demonstrated how ASP.NET Core Identity manages users, roles, and claims. UserManager handles users and user claims, RoleManager handles roles and role claims, and SignInManager can refresh the authentication session after identity data changes.
Roles are appropriate for broad, shared permission groups. Claims are useful for details such as departments, tenants, or individual permissions. A secure design creates these values only through trusted server-side operations and evaluates them through authorization policies. In the next stage, we will examine how this identity information is placed into JWT access tokens and used to protect API endpoints.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity
- https://learn.microsoft.com/en-us/aspnet/core/mvc/security/authorization/roles
- https://learn.microsoft.com/en-us/aspnet/core/mvc/security/authorization/claims
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addclaimsasync