.NET Auth Tutorial

Setting up authentication in .NET 10

A quick walkthrough of wiring ASP.NET Core Identity with cookie auth, protecting controllers, and adding a login page — the way I do it in every new project.

By admin Apr 16, 2026 3

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.
bash
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.
csharp
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

csharp
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.
csharp
[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

bash
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.