ASP.NET Core Documentation

Microsoft Learn: Building Secure Applications

Introduction to Authentication in ASP.NET Core

This tutorial provides an overview of authentication in ASP.NET Core applications. Authentication is the process of verifying the identity of a user or client. ASP.NET Core provides a flexible and extensible authentication system that supports various authentication schemes.

What is Authentication?

In web applications, authentication typically involves:

Authentication Schemes

ASP.NET Core's authentication middleware is highly modular. You can configure multiple authentication schemes to handle different types of authentication. Common schemes include:

Key Components

The authentication process in ASP.NET Core relies on several key components:

Configuring Authentication

Authentication is typically configured in the Program.cs (or Startup.cs in older versions) file. Here's a simplified example of how you might add cookie authentication:

// In Program.cs (for .NET 6 and later)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages(); // Or AddControllersWithViews()

builder.Services.AddAuthentication("MyAuthScheme") // Explicitly name your scheme
    .AddCookie("MyAuthScheme", options =>
    {
        options.LoginPath = "/Account/Login"; // The path to the login page
        options.LogoutPath = "/Account/Logout";
    });

builder.Services.AddAuthorization(); // Required for authorization

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// IMPORTANT: Authentication middleware must be added before UseAuthorization.
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages(); // Or app.MapControllerRoute(...)

app.Run();

Next Steps

Now that you have a foundational understanding of authentication in ASP.NET Core, you can explore specific authentication schemes in more detail: