MSDN Documentation

ASP.NET Core MVC & Razor Pages

Authentication & Authorization Samples

This section provides practical code examples demonstrating how to implement authentication and authorization in ASP.NET Core applications using both MVC and Razor Pages.

Implementing Authentication

Authentication is the process of verifying the identity of a user. ASP.NET Core offers flexible ways to handle this, including:

  • Cookie-based authentication
  • JWT (JSON Web Token) authentication
  • OAuth and OpenID Connect integration (e.g., Google, Facebook, Azure AD)
  • Identity Server for centralized authentication

Sample 1: Cookie-Based Authentication (Identity)

This sample demonstrates setting up ASP.NET Core Identity for cookie-based authentication, which is a common and robust choice for web applications.

// In Startup.cs or Program.cs (for .NET 6+)

// Add services to the container.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

// Add authentication services
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
        options.AccessDeniedPath = "/Account/AccessDenied";
    });

builder.Services.AddRazorPages(); // Or AddControllersWithViews() for MVC
builder.Services.AddControllersWithViews();

// Configure the HTTP request pipeline.
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

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

app.UseRouting();

// Add authentication and authorization middleware
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages(); // Or app.MapControllerRoute(...) for MVC
app.MapControllers();

app.Run();
                    

This setup configures ASP.NET Core Identity with a SQL Server database and enables cookie authentication, defining paths for login, logout, and access denied scenarios.

Implementing Authorization

Authorization determines what authenticated users are allowed to do. ASP.NET Core supports several authorization models:

  • Role-based authorization
  • Policy-based authorization (more flexible)
  • Claims-based authorization

Sample 2: Role-Based Authorization (Razor Pages)

This example shows how to restrict access to a Razor Page based on user roles.

// In a Razor Page (e.g., Pages/Admin/Dashboard.cshtml.cs)

using Microsoft.AspNetCore.Authorization;

[Authorize(Roles = "Admin,Editor")]
public class DashboardModel : PageModel
{
    public void OnGet()
    {
        // This page is only accessible by users in the 'Admin' or 'Editor' roles.
    }
}
                    

The [Authorize(Roles = "Admin,Editor")] attribute ensures that only users who are members of the specified roles can access this page.

Sample 3: Policy-Based Authorization (MVC)

Policy-based authorization allows for more complex authorization logic.

// In Startup.cs or Program.cs (for .NET 6+)

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RequireElevatedPrivileges", policy =>
        policy.RequireAuthenticatedUser()
              .RequireClaim("Department", "IT")
              .RequireRole("Manager"));
});

// In a Controller (e.g., Controllers/ReportsController.cs)
using Microsoft.AspNetCore.Authorization;

[Authorize(Policy = "RequireElevatedPrivileges")]
public class ReportsController : Controller
{
    public IActionResult ViewAllReports()
    {
        // This action is only accessible by authenticated users
        // who have a 'Department' claim of 'IT' AND are in the 'Manager' role.
        return View();
    }
}
                    

This policy combines multiple requirements: the user must be authenticated, have a specific claim, and belong to a particular role.

Note: For more advanced scenarios like API security with JWT, or integrating with external identity providers, refer to the official ASP.NET Core Security Documentation.

Key Takeaways

  • Use ASP.NET Core Identity for robust user management and authentication.
  • Leverage [Authorize] attributes on controllers, actions, or Razor Pages for straightforward authorization.
  • Define custom policies for complex authorization rules that combine roles, claims, or other requirements.
  • Ensure middleware is registered in the correct order (UseAuthentication before UseAuthorization).