Identity and cookie login
ASP.NET Core Identity is the tested, built-in way to handle users: password hashing, lockout, user tables and cookie login. This note shows why a home-made login breaks, how to switch Identity on with MapIdentityApi, how the encrypted cookie works, and how Login with Google plugs in.
57.1 The problem: a home-made login
- Passwords live in a dictionary in plain text.
- On login the user's email is put straight into a cookie; /profile trusts that cookie.
- Anyone can send user=admin@shop.in without a password and get "Hello admin@shop.in".
var app = WebApplication.Create(args);var users = new Dictionary<string, string> { ["riya@shop.in"] = "Riya@1234" };app.MapPost("/login", (Login r, HttpContext c) =>{ if (users.GetValueOrDefault(r.Email) != r.Password) return Results.Unauthorized(); c.Response.Cookies.Append("user", r.Email); return Results.Ok("Logged in");});app.MapGet("/profile", (HttpContext c) => c.Request.Cookies["user"] is { } u ? Results.Ok($"Hello {u}") : Results.Unauthorized());$ curl -i -b "user=admin@shop.in" localhost:5057/profileHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8"Hello admin@shop.in"- Step 1
1.Plain cookie: the client can write anything
- Step 2
2.Plain password: a DB leak leaks everything
- Step 3
3.No lockout: unlimited password guesses
We need a tested library = ASP.NET Core Identity
57.2 Setup: packages + IdentityDbContext
- Three packages: the Identity EF Core store, the SQLite provider and Google login.
- AppDbContext inherits IdentityDbContext<IdentityUser>, which already defines user, role and login tables.
- The migration creates 7 tables such as AspNetUsers and AspNetRoles.
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCoredotnet add package Microsoft.EntityFrameworkCore.Sqlitedotnet add package Microsoft.AspNetCore.Authentication.Googledotnet ef migrations add AddIdentitydotnet ef database updatepublic class AppDbContext( DbContextOptions<AppDbContext> options) : IdentityDbContext<IdentityUser>(options);Applying migration '20261106202636_AddIdentity'. CREATE TABLE "AspNetRoles" ( CREATE TABLE "AspNetUsers" ( CREATE TABLE "AspNetRoleClaims" ( CREATE TABLE "AspNetUserClaims" ( CREATE TABLE "AspNetUserLogins" ( CREATE TABLE "AspNetUserRoles" ( CREATE TABLE "AspNetUserTokens" (Done.57.3 Program.cs: Identity on
- AddIdentityApiEndpoints<IdentityUser>() registers password hashing, sign-in and cookie authentication in one go.
- AddEntityFrameworkStores<AppDbContext>() saves users through EF Core.
- MapIdentityApi creates ready endpoints: /register, /login, /refresh and more.
- RequireAuthorization protects /profile.
var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite("Data Source=shop.db"));builder.Services.AddAuthorization();builder.Services .AddIdentityApiEndpoints<IdentityUser>() .AddEntityFrameworkStores<AppDbContext>(); var app = builder.Build();app.MapIdentityApi<IdentityUser>();app.MapGet("/profile", (ClaimsPrincipal user) => $"Hello {user.Identity!.Name}") .RequireAuthorization();app.Run();57.4 Register: password policy + hash
- A weak password (aman123) gets 400 Bad Request: needs an uppercase letter and a non-alphanumeric character.
- A strong password gets 200 OK.
- The database has no password, only a PasswordHash: a salted PBKDF2 hash.
$ curl -i localhost:5057/register \ -H "Content-Type: application/json" \ -d '{"email":"aman@shop.in","password":"aman123"}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json{ "title": "One or more validation errors occurred.", "status": 400, "errors": { "PasswordRequiresNonAlphanumeric": ["Passwords must have at least one non alphanumeric character."], "PasswordRequiresUpper": ["Passwords must have at least one uppercase ('A'-'Z')."] } }$ curl -i localhost:5057/register \ -H "Content-Type: application/json" \ -d '{"email":"riya@shop.in","password":"Riya@1234"}'HTTP/1.1 200 OKContent-Length: 0$ dotnet run peek.csriya@shop.in | AQAAAAIAAYagAAAAEKVsH1b4LajXMB1VmhQ0mVoTIhTJpmk8HVxDUW6AdiSlu+Q0ul6Rq42nXehC+w2YSg==57.5 Login: an encrypted cookie
- ?useCookies=true asks for a cookie instead of a token; curl -c saves it to a jar file.
- The cookie .AspNetCore.Identity.Application holds a long encrypted value, with httponly and samesite=lax added automatically.
- With the cookie: Hello riya@shop.in. Without it: 401 Unauthorized.
$ curl -i -c jar.txt \ "localhost:5057/login?useCookies=true" \ -H "Content-Type: application/json" \ -d '{"email":"riya@shop.in","password":"Riya@1234"}'HTTP/1.1 200 OKContent-Length: 0Set-Cookie: .AspNetCore.Identity.Application=CfDJ8GLxwzfG0FhP...; expires=Fri, 20 Nov 2026 20:43:59 GMT; path=/; samesite=lax; httponly$ curl -i -b jar.txt localhost:5057/profileHTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Hello riya@shop.in$ curl -i localhost:5057/profileHTTP/1.1 401 UnauthorizedContent-Length: 0WWW-Authenticate: Bearer- Step 1
1.Register: salted hash -> AspNetUsers
- Step 2
2.Login: password verified, claims -> encrypted cookie
- Step 3
3.Every request: the browser sends the cookie
- Step 4
4.Middleware: decrypt -> User ready, RequireAuthorization passes
The cookie holds an encrypted ticket, never the password
57.6 Checkpoint: an edited cookie
- Writing admin@shop.in into the Identity cookie gives 401: the cookie is encrypted and signed.
- Without the server's secret key nobody can create a valid one; one changed character fails decryption and the request is anonymous.
$ curl -i localhost:5057/profile \ -b ".AspNetCore.Identity.Application=admin@shop.in"HTTP/1.1 401 UnauthorizedContent-Length: 0WWW-Authenticate: Bearer| Point | Home-made login | ASP.NET Core Identity |
|---|---|---|
| Password storage | Plain text | Salted PBKDF2 hash |
| Cookie | Plain email, editable | Encrypted + signed ticket |
| Cookie flags | None | httponly, samesite=lax (Secure with HTTPS) |
| Password policy / lockout | No | Yes, by default |
| Edited cookie | 200 Hello admin | 401 Unauthorized |
57.7 Login with Google
- AddGoogle with ClientId and ClientSecret from configuration (the OAuth flow is from the Web Basics login video).
- The endpoint returns Results.Challenge, which redirects to Google: 302 Found to accounts.google.com.
- The URL carries client_id, scope=openid profile email, response_type=code, PKCE code_challenge and state.
- /signin-google is handled by the Google middleware when Google returns with a code; SignInManager then links the Google user to an AspNetUsers row.
- A real login needs an OAuth client in Google Cloud Console; the demo uses a fake id and only shows the redirect.
builder.Services.AddAuthentication() .AddGoogle(o => { var cfg = builder.Configuration .GetSection("Authentication:Google"); o.ClientId = cfg["ClientId"]!; o.ClientSecret = cfg["ClientSecret"]!; }); app.MapGet("/login/google", () => Results.Challenge( new() { RedirectUri = "/profile" }, ["Google"]));$ curl -i localhost:5057/login/googleHTTP/1.1 302 FoundLocation: https://accounts.google.com/o/oauth2/v2/auth ?client_id=fake-id.apps.googleusercontent.com &scope=openid%20profile%20email &response_type=code &redirect_uri=http%3A%2F%2Flocalhost%3A5057%2Fsignin-google &code_challenge=u3ivyW_7f8Kzaek3m29gQvRkatiVvxJenWA7WFOZsSU &code_challenge_method=S256 &state=CfDJ8GLxwzfG0FhPo9K_BbY-MmlVSSabbAjo...Set-Cookie: .AspNetCore.Correlation.i6Iq53ON...=N; path=/signin-google; secure; samesite=none; httponly- Step 1
1.GET /login/google -> Results.Challenge
- Step 2
2.302 to accounts.google.com (client_id, scope, PKCE, state)
- Step 3
3.User signs in at Google
- Step 4
4.Google redirects to /signin-google with a code
- Step 5
5.Middleware exchanges the code, SignInManager links a local user
- Step 6
6.Cookie set, user lands on /profile (RedirectUri)
57.8 Common mistakes
- Putting ClientSecret in appsettings.json: it gets committed to Git and reaches everyone with repo access.
- Fix: dotnet user-secrets in development (stored outside the project folder), an environment variable or Key Vault in production.
- Thinking the bearer token from MapIdentityApi is a JWT: without useCookies it is an opaque encrypted token only for this app; other services need a JWT (next video).
- Thinking Identity is only for the Razor UI: it works with a pure API too.
dotnet user-secrets initdotnet user-secrets set \ "Authentication:Google:ClientSecret" \ "fake-secret"# production: environment variable# Authentication__Google__ClientSecret57.9 Rules for Identity
- Don't write login and password hashing yourself: use ASP.NET Core Identity.
- Browser apps: cookie login; in production confirm Secure and HttpOnly with HTTPS.
- Don't weaken the password policy and lockout defaults.
- Never commit secrets like ClientSecret.
- After an external login, link the user to your own database user.
57.10 Interview tips
- I use ASP.NET Core Identity with the EF Core store: salted PBKDF2 hashing, lockout and user management out of the box.
- For browser clients, cookie auth: the cookie is encrypted and signed, with HttpOnly, Secure and SameSite flags.
- MapIdentityApi gives /register and /login; useCookies=true returns a cookie, otherwise an opaque bearer token (not a JWT).
- External login via AddGoogle + Challenge; secrets live in user-secrets / Key Vault, never in code.