Why we need authentication
Most applications eventually need to know who the user is. ASP.NET Core ships with a full Identity stack that covers password hashing, cookies, account confirmation, and 2FA. In this post I will show the minimum wiring that gets you from a blank Web project to a working login page.
1. Install the packages
Add the Identity + EF Core packages to your Web project. If you scaffolded the app with the "Individual Accounts" template they are already there.
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Identity.UI
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
2. Extend your DbContext
Inherit from IdentityDbContext<IdentityUser> so Identity can store users/roles/claims alongside your domain tables. Same database, same migrations.
public class PortfolioDbContext : IdentityDbContext<IdentityUser>
{
public PortfolioDbContext(DbContextOptions<PortfolioDbContext> opts) : base(opts) { }
public DbSet<PROJECTS> PROJECTS { get; set; } = default!;
public DbSet<BLOG_POSTS> BLOG_POSTS { get; set; } = default!;
}
3. Register in Program.cs
services.AddDbContext<PortfolioDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<PortfolioDbContext>();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages(); // /Identity/Account/Login, /Register, etc.
4. Protect a controller
Use the [Authorize] attribute to gate an action. Unauthenticated users will be redirected to /Identity/Account/Login automatically.
[Authorize]
public class BlogController : Controller
{
public IActionResult Manage() => View();
}
Tip: keep public read actions open and put [Authorize] only on the write/admin endpoints. Easier to reason about than filtering by URL.
5. Run it
dotnet ef migrations add AddIdentity
dotnet ef database update
dotnet run
That is it. Browse to /Identity/Account/Register, create a user, sign in, and hit any [Authorize]-gated URL โ you are in.
