ASP.NET Core Identity is a membership system that allows you to add login functionality to your application. It includes features like user registration, password hashing, roles, claims, and multi-factor authentication.
ASP.NET Core Identity simplifies user management and security in web applications, providing essential tools to manage authentication and authorization efficiently.
Follow these steps:
// Open the NuGet Package Manager Console and run:
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
These packages provide Identity and Entity Framework Core functionality.
// Data/ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
}
The ApplicationDbContext
class inherits from IdentityDbContext
, enabling Identity features.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add Identity services
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.Run();
Identity is registered in the dependency injection container and configured to use the database.
// Add Identity's default UI:
dotnet add package Microsoft.AspNetCore.Identity.UI
// Create the migration:
dotnet ef migrations add InitialIdentity
// Apply the migration:
dotnet ef database update
This sets up the database schema required for Identity.
// Add default Razor Pages for Identity
app.MapRazorPages();
ASP.NET Core Identity provides pre-built Razor Pages for login, registration, and account management.
Visit /Identity/Account/Login
or /Identity/Account/Register
to use these pages.
// Pages/Admin.cshtml
@page
@attribute [Authorize(Roles = "Admin")]
Admin Panel
Use the [Authorize]
attribute to secure routes based on roles.
// Seed roles and users
public static async Task SeedData(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
var user = new IdentityUser { UserName = "admin@example.com", Email = "admin@example.com" };
var result = await userManager.CreateAsync(user, "Admin@123");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
Call SeedData
during application startup to seed roles and users.