Quick start: add cookie sign-in to an API
In this tutorial we build a minimal API. A user registers, confirms their email, signs in with a cookie, calls a protected route, and signs out. We use curl as the client, so we need no front end.
We use the password facade: AddPasswordAuth, UseAuthEndpoints, and MapPasswordAuth. The session is a cookie. Passkeys stay off. Other setups are on Choose your sign-in setup.
Prerequisites
- The .NET 10 SDK. AuthEndpoints targets
net10.0. Rundotnet --versionto check. The output starts with10.. curl.
Create the project
Create an empty web project and add the packages:
dotnet new web -n AuthDemo
cd AuthDemo
dotnet add package AuthEndpoints
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Each dotnet add package command ends with a Restored ... AuthDemo.csproj line. SQLite lets us run the tutorial without a database server. Any EF Core provider works.
Replace Program.cs
Replace Program.cs with this file:
using AuthEndpoints;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite("Data Source=app.db"));
builder.Services.AddPasswordAuth<AppUser, AppDbContext>();
builder.Services.AddTransient<IEmailSender<AppUser>, ConsoleEmailSender>();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();
}
app.UseAuthEndpoints();
app.MapPasswordAuth<AppUser>();
app.MapGet("/me", (System.Security.Claims.ClaimsPrincipal user) => new { email = user.Identity!.Name })
.RequireAuthorization();
app.Run();
public class AppUser : IdentityUser { }
public class AppDbContext(DbContextOptions<AppDbContext> options) : IdentityDbContext<AppUser>(options) { }
public class ConsoleEmailSender(ILogger<ConsoleEmailSender> logger) : IEmailSender<AppUser>
{
public Task SendConfirmationLinkAsync(AppUser user, string email, string confirmationLink)
{
logger.LogInformation("Confirm {Email}: {Link}", email, confirmationLink);
return Task.CompletedTask;
}
public Task SendPasswordResetLinkAsync(AppUser user, string email, string resetLink)
{
logger.LogInformation("Reset link for {Email}: {Link}", email, resetLink);
return Task.CompletedTask;
}
public Task SendPasswordResetCodeAsync(AppUser user, string email, string resetCode)
{
logger.LogInformation("Reset code for {Email}: {Code}", email, resetCode);
return Task.CompletedTask;
}
}
Here is what the AuthEndpoints calls do:
AddPasswordAuth<AppUser, AppDbContext>registers Identity, password sign-up, sign-in, recovery, account management, and the cookie session.UseAuthEndpointsadds authentication, authorization, rate limiting, and antiforgery. In a real app, call it after your exception-handling middleware.MapPasswordAuth<AppUser>maps the routes under/auth.
ConsoleEmailSender writes links to the log so we can follow them by hand. EnsureCreated builds the schema without migrations. Both are for this tutorial. See Prepare for production before you deploy.
Run the app
dotnet run
The log shows the CREATE TABLE commands from EnsureCreated, then these lines:
warn: AuthEndpoints[0]
IAccountSecurityEmailSender is LoggingAccountSecurityEmailSender, which logs password-set and registration-attempt notices and does not send mail. Register an implementation to deliver them.
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5265
The warning is expected in this tutorial. The port comes from Properties/launchSettings.json and is different in each new project. The commands below use http://localhost:5265. Replace it with your URL, or start the app with dotnet run --urls http://localhost:5265. Open a second terminal for the curl commands.
Register a user
curl -i -H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"Passw0rd!"}' \
http://localhost:5265/auth/register
The response is 200 OK with an empty body. AuthEndpoints requires a confirmed account by default, so POST /auth/login returns 401 Unauthorized until the user confirms the email.
Confirm the email
Find the Confirm ada@example.com line in the app log and copy the link. The sender receives the link HTML-encoded, so & appears as &. Change & back to &, then open the link:
curl -i "http://localhost:5265/auth/confirmEmail?userId=...&code=..."
The response is 200 OK with the body Thank you for confirming your email. If you leave & in the link, the response is 400 Bad Request.
Sign in
curl -i -c cookies.txt -b cookies.txt -H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"Passw0rd!"}' \
http://localhost:5265/auth/login
The response is 200 OK with an empty body and a Set-Cookie: .AspNetCore.Identity.Application=... header. curl stores the cookie in cookies.txt. POST /auth/login does not use a CSRF token.
Call the protected endpoint with the cookie:
curl -b cookies.txt http://localhost:5265/me
The response is {"email":"ada@example.com"}.
Sign out
Sign-out changes state on a cookie session, so it needs a CSRF token. Try it without one first:
curl -i -c cookies.txt -b cookies.txt -X POST http://localhost:5265/auth/logout
The response is 400 Bad Request with the body "Invalid or missing CSRF token.". Get a token, then send it in the RequestVerificationToken header:
curl -c cookies.txt -b cookies.txt http://localhost:5265/auth/csrfToken
The response is {"csrfToken":"..."}.
curl -i -c cookies.txt -b cookies.txt -X POST \
-H "RequestVerificationToken: <csrfToken from the previous response>" \
http://localhost:5265/auth/logout
The response is 200 OK with an empty body. Call /me again:
curl -i -b cookies.txt http://localhost:5265/me
The response is 401 Unauthorized.
Logout, account changes, step-up, and passkey ceremonies need that token. Login, register, forgot-password, and reset-password do not. The list is on Antiforgery (CSRF) rules.
What you built
You have an API with password registration, email confirmation, cookie sign-in, and CSRF-protected sign-out. The same host also maps account management, two-factor authentication, password reset, and step-up under /auth. See Password auth for what this facade maps, and Endpoint reference for every route.
Next
- Choose your sign-in setup for JWT, passkeys, email codes, GitHub, Google, or a custom mix
- Register users and Sign users in
- Prepare for production