Table of Contents
Setting up ASP.NET Identity with Entity Framework is a fundamental step for securing your ASP.NET Core applications. This tutorial provides a comprehensive guide to integrating Identity for authentication and authorization.
Prerequisites
- Visual Studio 2022 or later
- .NET 6.0 SDK or later
- Basic knowledge of ASP.NET Core MVC
- Entity Framework Core familiarity
Creating a New ASP.NET Core Project
Start by creating a new ASP.NET Core Web Application in Visual Studio. Choose the "Web Application (Model-View-Controller)" template and ensure that Authentication is set to "Individual User Accounts".
Configuring Entity Framework Core
Entity Framework Core is integrated with ASP.NET Identity by default. Verify that your Startup.cs or Program.cs includes the necessary services.
In Program.cs, ensure the following code exists:
builder.Services.AddDbContext
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
And in appsettings.json, define the connection string:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-YourAppName;Trusted_Connection=True;MultipleActiveResultSets=true"
Adding Identity Services
In Program.cs, add Identity services:
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Creating the ApplicationDbContext
Ensure your ApplicationDbContext.cs inherits from IdentityDbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
}
Applying Migrations and Updating Database
Open the Package Manager Console and run:
Add-Migration InitialCreate
Update-Database
Testing Authentication
Run the application. Register a new user and verify login functionality. The Identity system is now integrated with Entity Framework Core, providing secure user management.
Conclusion
Integrating ASP.NET Identity with Entity Framework Core streamlines user authentication and management. Customize the Identity models to extend user properties as needed for your application.