.NET Core – Razor Pages Auth Tutorial

This tutorial walks you through adding authentication to a Razor Pages application using ASP.NET Core Identity. By the end you'll have a secure site with login, registration, and external provider support.

Table of Contents

Prerequisites

Make sure you have the following installed:

Create a Razor Pages Project

Open a terminal and run:

dotnet new webapp -o RazorAuthDemo

Add ASP.NET Core Identity

Install the Identity package and scaffold the UI:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet aspnet-codegenerator identity -dc RazorAuthDemo.Data.ApplicationDbContext --files "Account.Register;Account.Login" -f

Update Program.cs

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

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

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
    options.AccessDeniedPath = "/Account/AccessDenied";
});

Configure Cookie Authentication

The AddDefaultIdentity call already registers cookie authentication. You can further customize the cookie settings in Program.cs as shown above.

Protect Pages with [Authorize]

To restrict a page to authenticated users, add the @attribute [Authorize] directive at the top of the Razor page:

@page
@model SecureModel
@attribute [Authorize]

Welcome, @User.Identity.Name!

Add External Login (Google)

Register your app with Google and obtain a Client ID and Secret. Then add the following to Program.cs:

builder.Services.AddAuthentication()
    .AddGoogle(googleOptions =>
    {
        googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
        googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
    });

Finally, add the Google button to your login page:

<partial name="_LoginPartial" />
<a asp-page="/Account/ExternalLogin" asp-route-provider="Google" class="btn btn-outline-primary">Login with Google</a>

Testing the Flow

  1. Run the app: dotnet run
  2. Navigate to /Secure – you should be redirected to the login page.
  3. Register a new account, then log in.
  4. Return to /Secure – you’ll see the protected content.
  5. Click Login with Google to test external auth.

Congratulations! You have a fully functional authentication system in your Razor Pages app.