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.
Make sure you have the following installed:
Open a terminal and run:
dotnet new webapp -o RazorAuthDemo
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
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";
});
The AddDefaultIdentity
call already registers cookie authentication. You can further customize the cookie settings in Program.cs
as shown above.
[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!
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>
dotnet run
/Secure
– you should be redirected to the login page./Secure
– you’ll see the protected content.Congratulations! You have a fully functional authentication system in your Razor Pages app.