ASP.NET Core Identity

• By OmerZ Solutions

Security is one of the most important requirements in modern web applications. Applications must protect user information, control access, and provide secure authentication mechanisms.

ASP.NET Core Identity provides a complete membership system that simplifies user authentication, authorization, password management, roles, claims, and security features for .NET applications.

ASP.NET Core Identity
ASP.NET Core Identity is a membership framework that provides ready-to-use APIs for managing users, passwords, roles, claims, authentication, and authorization in ASP.NET Core applications.

What is ASP.NET Core Identity?

ASP.NET Core Identity is a framework provided by Microsoft that manages user accounts and security-related operations in ASP.NET Core applications.

Instead of manually creating tables, password encryption logic, and user management features, developers can use Identity components that are already designed according to modern security practices.

Why ASP.NET Core Identity is Important

Authentication and authorization are required in almost every enterprise application. Building these features manually can introduce security risks and increase development complexity.

Benefits of ASP.NET Core Identity

  • Secure user authentication
  • Built-in password hashing
  • Role management
  • Claims-based security
  • Account confirmation support
  • Password recovery features
  • Two-factor authentication support
  • Integration with Entity Framework Core

Authentication vs Authorization

Authentication and authorization are two different security concepts.

Authentication Authorization
Verifies user identity Determines user permissions
Example: Login with username and password Example: Admin access to dashboard
Answers "Who are you?" Answers "What can you access?"

ASP.NET Core Identity Architecture

ASP.NET Core Identity is built using several components that work together to provide complete user management.

Main Identity Components

  • User Management
  • Roles
  • Claims
  • Authentication Cookies
  • Security Tokens
  • User Stores
  • Entity Framework Core Integration

Identity User Management

The User class represents application users. Identity stores user information such as username, email, password hash, and security details.

Default Identity User



public class IdentityUser
{
	public string Id { get; set; }
	public string UserName { get; set; }
	public string Email { get; set; }
	public string PasswordHash { get; set; }
}

Creating ASP.NET Core Identity Project

Identity can be added to a new ASP.NET Core application using Visual Studio or .NET CLI tools.

Create MVC Project



dotnet new mvc -n IdentityDemo

Install Identity Package



dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Configuring Identity in ASP.NET Core

Identity services are registered inside Program.cs using the built-in dependency injection system.



builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

Important: Identity automatically integrates with ASP.NET Core Dependency Injection and Entity Framework Core for user management and database operations.

Setting Up Identity Database with Entity Framework Core

ASP.NET Core Identity stores user information, roles, claims, and authentication data inside a database. Entity Framework Core is commonly used as the storage provider.

Creating Identity DbContext



public class ApplicationDbContext : IdentityDbContext
{

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
{

}

}

Register Database Context



builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
	options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
}
);

Create Identity Database Migration



dotnet ef migrations add CreateIdentityTables
dotnet ef database update

ASP.NET Core Identity Database Tables

After migration, Identity creates several tables that manage user security information.

Table Purpose
AspNetUsers Stores user accounts
AspNetRoles Stores application roles
AspNetUserRoles Maps users with roles
AspNetUserClaims Stores user claims
AspNetRoleClaims Stores role permissions
AspNetUserTokens Stores authentication tokens

Creating Custom Identity User Model

Most enterprise applications require additional user information such as first name, last name, profile image, or employee details.

Custom User Class Example



public class ApplicationUser : IdentityUser
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public DateTime CreatedDate { get; set; }
}

Update DbContext



public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
	public ApplicationDbContext(DbContextOptions options) : base(options)
	{

	}
}

Configure Custom User



builder.Services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

User Registration with ASP.NET Core Identity

User registration creates a new account and stores the user's information securely in the Identity database.

Registration Model



public class RegisterViewModel
{
	public string Email { get; set; }
	public string Password { get; set; }
	public string ConfirmPassword { get; set; }
}

Creating User Account



public class AccountController : Controller
{

private readonly UserManager <ApplicationUser> _userManager;

public AccountController(UserManager<ApplicationUser> userManager)
{
	_userManager = userManager;
}

[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
	var user = new ApplicationUser{UserName = model.Email, Email = model.Email};
	var result = await _userManager.CreateAsync(user, model.Password);

	if(result.Succeeded)
	{
		return RedirectToAction("Login");
	}

	return View(model);
}

}

Password Security in ASP.NET Core Identity

ASP.NET Core Identity never stores passwords as plain text. Passwords are automatically hashed before being saved.

Identity uses secure hashing algorithms and provides configurable password policies.

Configure Password Rules



builder.Services.AddIdentity<ApplicationUser,IdentityRole>(options =>
{
	options.Password.RequiredLength = 8;
	options.Password.RequireDigit = true;
	options.Password.RequireUppercase = true;
	options.Password.RequireLowercase = true;
	options.Password.RequireNonAlphanumeric = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();

User Login Implementation

Login verifies user credentials and creates an authenticated session.

Login Example



public async Task<IActionResult> Login(LoginViewModel model)
{

var user = await _userManager.FindByEmailAsync(model.Email);

if(user != null)
{
	var result = await _signInManager.PasswordSignInAsync(user,model.Password,false,false);
	if(result.Succeeded)
	{
		return RedirectToAction("Index","Home");
	}
}

return View(model);

}

User Logout

ASP.NET Core Identity provides built-in functionality for ending authenticated sessions.



await _signInManager.SignOutAsync();

Role Management in ASP.NET Core Identity

Roles allow applications to control access based on user categories such as Admin, Manager, Customer, or Employee.

Creating a Role



await _roleManager.CreateAsync(new IdentityRole("Admin"));

Assign Role to User



await _userManager.AddToRoleAsync(user,"Admin");

Role-Based Authorization

Controllers and actions can be protected using the Authorize attribute.



[Authorize(Roles="Admin")]
public IActionResult AdminDashboard()
{
	return View();
}

Claims-Based Authorization in ASP.NET Core Identity

Claims provide additional information about a user. Unlike roles that usually represent a group, claims represent specific user properties or permissions.

Examples of claims include department name, access level, subscription type, or custom application permissions.

Adding a User Claim



var claim = new Claim("Department","IT");
await _userManager.AddClaimAsync(user,claim);

Reading User Claims



var department = User.Claims.FirstOrDefault(x => x.Type == "Department")?.Value;

Policy-Based Authorization

Policy-based authorization provides a flexible way to create custom security rules based on claims and requirements.

Creating Authorization Policy



builder.Services.AddAuthorization(options =>
{
	options.AddPolicy("RequireAdmin",policy =>policy.RequireRole("Admin"));
});

Using Policy Authorization



[Authorize(Policy="RequireAdmin")]
public IActionResult SecurePage()
{
	return View();
}

Protecting ASP.NET Core Web API Endpoints

ASP.NET Core Identity can be combined with API authentication to secure backend services and enterprise applications.

Securing Controller Action



[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{

[Authorize]
[HttpGet]
public IActionResult GetOrders()
{
	return Ok();
}

}

JWT Authentication with ASP.NET Core Identity

For Web APIs, mobile applications, and distributed systems, JWT tokens are commonly used instead of cookie-based authentication.

JWT authentication allows clients to send a secure token with every request.

Install JWT Package



dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Configure JWT Authentication



builder.Services.AddAuthentication(options =>
{

options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})
.AddJwtBearer(options =>
{

options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};

});

Generating JWT Token After Login



private string GenerateToken(ApplicationUser user)
{

var claims =
new[]
{

new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Email, user.Email)

};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(claims: claims,expires:DateTime.Now.AddHours(1),signingCredentials:credentials);

return new JwtSecurityTokenHandler().WriteToken(token);

}

Security Recommendation: Never store JWT secret keys directly in source code. Use secure configuration providers, environment variables, or secret management systems.

Email Confirmation in ASP.NET Core Identity

Email confirmation verifies that users own the email address used during registration.

This prevents fake accounts and improves application security.

Generate Email Confirmation Token



var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

Confirm Email



await _userManager.ConfirmEmailAsync(user,token);

Password Reset Functionality

ASP.NET Core Identity provides built-in APIs for secure password recovery.

Generate Reset Token



var token = await _userManager.GeneratePasswordResetTokenAsync(user);

Reset Password



await _userManager.ResetPasswordAsync(user,token,newPassword);

Two-Factor Authentication (2FA)

Two-factor authentication adds an additional security layer by requiring a second verification step after password authentication.

Common second factors include:

  • Authenticator applications
  • SMS verification
  • Email verification codes

Enable Two Factor Authentication



await _userManager.SetTwoFactorEnabledAsync(user,true);

ASP.NET Core Identity in Web API Applications

Identity is commonly used in REST APIs to provide secure user registration, login, authorization, and token-based authentication.

ASP.NET Core Identity with Clean Architecture

Clean Architecture separates identity management from business logic while keeping security concerns organized.

The application layer communicates through interfaces while Identity-specific implementation details remain inside the infrastructure layer.

Customizing ASP.NET Core Identity

ASP.NET Core Identity provides default UI components, but enterprise applications often require customized registration pages, login screens, and security workflows.

Developers can customize:

  • Login pages
  • Registration forms
  • User profile management
  • Password policies
  • Email workflows

ASP.NET Core Identity Security Best Practices

Security should always be a priority when implementing authentication systems. ASP.NET Core Identity provides many built-in security features, but proper configuration is required for enterprise applications.

1. Use Strong Password Policies

Applications should enforce strong password requirements to reduce the risk of account compromise.

  • Require minimum password length
  • Require uppercase and lowercase characters
  • Require numbers and special characters
  • Prevent commonly used passwords

2. Enable HTTPS

Authentication data and security tokens should always be transmitted over secure HTTPS connections.

3. Protect Sensitive User Information

Avoid storing unnecessary personal information and never store passwords in plain text. ASP.NET Core Identity automatically handles secure password hashing.

4. Use Account Lockout Features

Account lockout helps protect applications from repeated failed login attempts.


 
builder.Services.AddIdentity(options =>
{
	options.Lockout.MaxFailedAccessAttempts = 5;
	options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
}
);

5. Secure Authentication Cookies

Cookie settings should be configured carefully to protect authenticated sessions.



builder.Services.ConfigureApplicationCookie(options =>
{
	options.Cookie.HttpOnly = true;
	options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

Common ASP.NET Core Identity Mistakes

  • Creating custom authentication instead of using built-in security features
  • Storing passwords manually
  • Using weak password policies
  • Ignoring email verification
  • Giving users unnecessary permissions
  • Not implementing account recovery securely
  • Hardcoding security keys and secrets
  • Skipping authorization checks on APIs

Enterprise ASP.NET Core Identity Architecture

Large applications usually require a structured identity architecture to support thousands or millions of users.

Enterprise systems may also integrate with external identity providers such as OAuth, OpenID Connect, or corporate authentication platforms.

Identity Integration with External Providers

ASP.NET Core Identity supports external authentication providers that allow users to sign in using existing accounts.

Common providers include:

  • Google Authentication
  • Microsoft Account
  • Facebook Login
  • Enterprise Identity Providers

Example External Authentication Registration



builder.Services.AddAuthentication()
.AddGoogle(options =>
{
	options.ClientId = "GoogleClientId";
	options.ClientSecret = "GoogleSecret";
});

ASP.NET Core Identity Checklist

  • Configure Identity with Entity Framework Core
  • Use custom user models when required
  • Implement proper password policies
  • Use roles and claims correctly
  • Protect sensitive API endpoints
  • Enable email confirmation
  • Use JWT authentication for APIs
  • Implement two-factor authentication when needed
  • Store secrets securely
  • Regularly review user permissions

Frequently Asked Questions About ASP.NET Core Identity

What is ASP.NET Core Identity used for?

ASP.NET Core Identity is used for managing user accounts, authentication, authorization, passwords, roles, claims, and security features in ASP.NET Core applications.

Is ASP.NET Core Identity secure?

Yes. ASP.NET Core Identity provides secure password hashing, token generation, account management, and authentication features designed for modern applications.

Can ASP.NET Core Identity be used with Web APIs?

Yes. Identity can be combined with JWT authentication to secure ASP.NET Core Web APIs and mobile application backends.

What is the difference between Identity and JWT?

Identity manages users, passwords, roles, and security information. JWT is an authentication token format commonly used to send user identity information between clients and APIs.

Can Identity tables be customized?

Yes. Developers can extend Identity classes such as ApplicationUser and ApplicationRole to store additional application-specific information.

Conclusion

ASP.NET Core Identity provides a powerful and secure foundation for building modern applications that require authentication and authorization.

With built-in support for user management, password security, roles, claims, tokens, and external authentication providers, developers can create reliable security systems without implementing everything from scratch.

By following best practices and integrating Identity with modern architectural patterns such as Clean Architecture and Dependency Injection, organizations can build secure and scalable enterprise applications.

Need Help Building Secure ASP.NET Core Applications?

OmerZ Solutions helps businesses develop secure, scalable, and enterprise-grade .NET applications with modern authentication and authorization solutions.

Contact Us