# Authentication

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Application Security
Source: https://www.devtutorials.ai/learn/blazor/application-security/authentication

> Find out who the user is: cookies and their security options, cookies in Blazor, the cookie authentication scheme and claims, ASP.NET Core Identity, password hashing with salt, register, login and logout, AuthenticationStateProvider, cascading authentication state and ClaimsPrincipal.

## Authentication Overview

- **Authentication** means finding out **who** the user is. Logging in is authentication.
- The user proves it with **credentials**: something only they know or have, like an email and a password.
- **Authorization** is the next step: deciding what that user **may do**. You learn it in the next lesson.
- HTTP **forgets** everything between requests. So after login, the server gives the browser a small **ticket**, and the browser shows it with every request. In ASP.NET Core, that ticket is a **cookie**.

**Real-World Example:**

Ravi logs in to the Tea Shop with his email and password. The server checks them and hands back a login cookie. From then on, every page he opens sends the cookie, so the server knows it is Ravi and shows **his** orders.

<figure className="blz-fig">
<svg viewBox="0 0 640 215" role="img" aria-labelledby="fig-auth-flow">
  <title id="fig-auth-flow">Animation: 1. The browser sends an email and a password to the server. 2. The server checks them and answers with a login cookie. 3. Every later request carries the cookie, and the server answers: Hello, Ravi.</title>
  <defs><marker id="fig-auth-flow-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="30" width="130" height="170" rx="12" />
  <text className="t m" x="75" y="56" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Browser</text>
  <rect className="pur" x="500" y="30" width="130" height="170" rx="12" />
  <text className="t m" x="565" y="56" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Server</text>
  <text className="t" x="565" y="80" textAnchor="middle" style={{ fontSize: 10 }}>checks the password</text>
  <path className="line" d="M140 90 H496" markerEnd="url(#fig-auth-flow-a)" />
  <text className="t m" x="320" y="84" textAnchor="middle" style={{ fontSize: 11 }}>1. log in: email + password</text>
  <path className="line" d="M500 130 H144" markerEnd="url(#fig-auth-flow-a)" />
  <text className="t m" x="320" y="124" textAnchor="middle" style={{ fontSize: 11 }}>2. here is your login cookie</text>
  <path className="line" d="M140 170 H496" markerEnd="url(#fig-auth-flow-a)" />
  <text className="t m" x="320" y="164" textAnchor="middle" style={{ fontSize: 11 }}>3. GET /orders + cookie: "It is Ravi"</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="140;500;500;140;140;500;500" keyTimes="0;0.25;0.33;0.58;0.66;0.92;1" dur="7s" repeatCount="indefinite" />
    <animate attributeName="cy" values="90;90;130;130;170;170;170" keyTimes="0;0.25;0.33;0.58;0.66;0.92;1" dur="7s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Log in once, get a cookie, and show it with every request.</figcaption>
</figure>

## Cookies

### What Cookies Are

- A **cookie** is a small piece of named text that a website asks the browser to keep, like `theme=dark`.
- The server sets it with a **`Set-Cookie`** header on a response. (A **header** is an extra line of information on a request or response.)
- After that, the browser sends it back by itself, in a **`Cookie`** header, with **every** request to the same site.
- Cookies are used for login, remembering choices (language, theme) and shopping carts.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-cookie-headers">
  <title id="fig-cookie-headers">Two steps. First, the server answers a request with the header Set-Cookie: theme=dark, and the browser stores it in its cookie jar. Second, on the next request the browser adds the header Cookie: theme=dark by itself.</title>
  <defs><marker id="fig-cookie-headers-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="20" width="150" height="160" rx="12" />
  <text className="t m" x="85" y="44" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Browser</text>
  <rect className="org" x="30" y="110" width="110" height="50" rx="10" />
  <text className="t m" x="85" y="131" textAnchor="middle" style={{ fontSize: 11 }}>cookie jar</text>
  <text className="t" x="85" y="149" textAnchor="middle" style={{ fontSize: 11 }}>theme=dark</text>
  <rect className="pur" x="480" y="20" width="150" height="160" rx="12" />
  <text className="t m" x="555" y="44" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Server</text>
  <path className="line" d="M480 75 H164" markerEnd="url(#fig-cookie-headers-a)" />
  <text className="t m" x="320" y="68" textAnchor="middle" style={{ fontSize: 11 }}>1. response: Set-Cookie: theme=dark</text>
  <path className="line" d="M160 135 H476" markerEnd="url(#fig-cookie-headers-a)" />
  <text className="t m" x="320" y="128" textAnchor="middle" style={{ fontSize: 11 }}>2. next request: Cookie: theme=dark</text>
</svg>
<figcaption>The server sets a cookie once. The browser sends it back every time.</figcaption>
</figure>

### Managing Cookies

On the server, the current request (`HttpContext`, see **Middleware Pipeline**) gives you three things:

| Job | Code |
|---|---|
| Set (create or change) | `context.Response.Cookies.Append("theme", "dark", options)` |
| Read | `context.Request.Cookies["theme"]` (null if it is not there) |
| Delete | `context.Response.Cookies.Delete("theme")` |

- Deleting really means "tell the browser it has expired", so the browser throws it away.
- You can see a site's cookies in the browser: press **F12**, open **Application** (Chrome, Edge) or **Storage** (Firefox), then **Cookies**.

In the below example, the page sets, reads and deletes a real `theme` cookie in your browser. The small `cookies.js` file does the cookie work, and C# calls it with JS interop (see **JavaScript Interop**).

<button @onclick="Read">Read theme</button>
<button @onclick="Delete">Delete theme</button>

<p>theme cookie: @(theme == "" ? "(none)" : theme)</p>

@code {
      private string theme = "";

      private async Task Save()
      {
          // name, value, and how many seconds the browser keeps it
          await JS.InvokeVoidAsync("cookies.set", "theme", "dark", 3600);
          await Read();
      }

      private async Task Read()
      {
          theme = await JS.InvokeAsync<string>("cookies.get", "theme");
      }

      private async Task Delete()
      {
          await JS.InvokeVoidAsync("cookies.remove", "theme");
          await Read();
      }
}
`,
    "wwwroot/js/cookies.js": `// Small helpers so C# can read and write cookies (through JS interop)
window.cookies = {
      set: function (name, value, seconds) {
          document.cookie = name + "=" + encodeURIComponent(value) +
              "; max-age=" + seconds + "; path=/; samesite=lax";
      },
      get: function (name) {
          var parts = document.cookie.split("; ");
          for (var i = 0; i < parts.length; i++) {
              var pair = parts[i].split("=");
              if (pair[0] === name) return decodeURIComponent(pair[1]);
          }
          return "";
      },
      remove: function (name) {
          document.cookie = name + "=; max-age=0; path=/";
      }
};
`,
  }}
/>

### Cookie Security Options

A login cookie is like a house key, so it must be protected. Each cookie can carry these options:

| Option | What it does | Protects against |
|---|---|---|
| **HttpOnly** | JavaScript cannot read the cookie | Bad scripts that steal cookies |
| **Secure** | Sent only over HTTPS | People reading the network |
| **SameSite** | Not sent when another site starts the request (`Lax` or `Strict`) | Fake requests from other sites |
| **Expires** / **Max-Age** | When the browser throws it away | Logins that last forever |

<figure className="blz-fig">
<svg viewBox="0 0 640 185" role="img" aria-labelledby="fig-cookie-options">
  <title id="fig-cookie-options">One Set-Cookie header split into labelled parts: the name and value .AspNetCore.Cookies=CfDJ8..., then expires (when it ends), secure (HTTPS only), samesite=lax (not from other sites) and httponly (hidden from JavaScript).</title>
  <defs><marker id="fig-cookie-options-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="10" y="30" width="620" height="44" rx="10" />
  <text className="t m" x="22" y="57" style={{ fontSize: 12 }}>Set-Cookie: .AspNetCore.Cookies=CfDJ8...; expires=...; secure; samesite=lax; httponly</text>
  <rect className="blu" x="10" y="110" width="140" height="56" rx="10" />
  <text className="t m" x="80" y="134" textAnchor="middle" style={{ fontSize: 11 }}>name = value</text>
  <text className="t" x="80" y="152" textAnchor="middle" style={{ fontSize: 10 }}>the ticket itself</text>
  <rect className="org" x="170" y="110" width="105" height="56" rx="10" />
  <text className="t m" x="222" y="134" textAnchor="middle" style={{ fontSize: 11 }}>expires</text>
  <text className="t" x="222" y="152" textAnchor="middle" style={{ fontSize: 10 }}>when it ends</text>
  <rect className="grn" x="295" y="110" width="100" height="56" rx="10" />
  <text className="t m" x="345" y="134" textAnchor="middle" style={{ fontSize: 11 }}>secure</text>
  <text className="t" x="345" y="152" textAnchor="middle" style={{ fontSize: 10 }}>HTTPS only</text>
  <rect className="pur" x="415" y="110" width="105" height="56" rx="10" />
  <text className="t m" x="467" y="134" textAnchor="middle" style={{ fontSize: 11 }}>samesite=lax</text>
  <text className="t" x="467" y="152" textAnchor="middle" style={{ fontSize: 10 }}>not from other sites</text>
  <rect className="blu" x="540" y="110" width="90" height="56" rx="10" />
  <text className="t m" x="585" y="134" textAnchor="middle" style={{ fontSize: 11 }}>httponly</text>
  <text className="t" x="585" y="152" textAnchor="middle" style={{ fontSize: 10 }}>no JavaScript</text>
</svg>
<figcaption>The options travel with the cookie in the Set-Cookie header.</figcaption>
</figure>

On the server, you set them with **`CookieOptions`**:

{
      context.Response.Cookies.Append("theme", "dark", new CookieOptions
      {
          HttpOnly = true,                              // hidden from JavaScript
          Secure = true,                                // HTTPS only
          SameSite = SameSiteMode.Lax,                  // not sent by other sites' requests
          Expires = DateTimeOffset.UtcNow.AddDays(30)   // kept for 30 days
      });
      return "Saved";
});
`}
/>

- Without `Expires`, the cookie is a **session cookie**: it goes away when the browser is closed.
- The login cookie that ASP.NET Core makes is already `HttpOnly`, `Secure` and `SameSite=Lax`.

In the below example, a `promo` cookie gets a **Max-Age** of 5 seconds. Click the button and watch the browser throw it away.

<ul>
      @foreach (var line in lines)
      {
          <li>@line</li>
      }
</ul>

@code {
      private List<string> lines = new();

      private async Task SaveShortCookie()
      {
          lines.Clear();
          await JS.InvokeVoidAsync("cookies.set", "promo", "FREE-CHAI", 5);

          for (int second = 0; second <= 7; second++)
          {
              var value = await JS.InvokeAsync<string>("cookies.get", "promo");
              lines.Add("After " + second + " s: " + (value == "" ? "gone" : value));
              StateHasChanged();
              await Task.Delay(1000);
          }
      }
}
`,
    "wwwroot/js/cookies.js": `// Small helpers so C# can read and write cookies (through JS interop)
window.cookies = {
      set: function (name, value, seconds) {
          document.cookie = name + "=" + encodeURIComponent(value) +
              "; max-age=" + seconds + "; path=/; samesite=lax";
      },
      get: function (name) {
          var parts = document.cookie.split("; ");
          for (var i = 0; i < parts.length; i++) {
              var pair = parts[i].split("=");
              if (pair[0] === name) return decodeURIComponent(pair[1]);
          }
          return "";
      },
      remove: function (name) {
          document.cookie = name + "=; max-age=0; path=/";
      }
};
`,
  }}
/>

The demo cookies here are **not** HttpOnly, because JavaScript has to read them. Never keep login tickets or other secrets in a cookie that JavaScript can read.

### Using Cookies in Blazor

Where your code runs decides how it can reach cookies:

| Where | How |
|---|---|
| **Static server rendering** (no interactivity) | Read and set cookies through `HttpContext`, which the page gets as a `[CascadingParameter]` |
| **Interactive** (Server or WebAssembly) | There is no `HttpContext` per click. Use JS interop for non-HttpOnly cookies, as in the boxes above |
| **Login** | Let ASP.NET Core make and read the login cookie for you (next section) |

In the below code, a static page reads the `theme` cookie from the request:

@code {
      // Only set during static server rendering, null in interactive mode
      [CascadingParameter]
      public HttpContext? HttpContext { get; set; }

      private string theme = "light";

      protected override void OnInitialized()
      {
          theme = HttpContext?.Request.Cookies["theme"] ?? "light";
      }
}
`}
/>

- This page has no `@rendermode`, so it runs as a static page and `HttpContext` is set.
- In an interactive component, `HttpContext` is **null**. Do not rely on it there.

## Cookie Authentication

### Cookie Authentication Scheme

- An **authentication scheme** is a named way to find out who the user is. The cookie scheme is named **`"Cookies"`**.
- With it, ASP.NET Core does the cookie work for you. After login, it writes one **encrypted** login cookie (scrambled, so nobody can read or change it). On each request, it reads the cookie back and knows the user.
- Inside the cookie is the user, described by **claims**.

Three new words describe a user in .NET:

| Word | Meaning | Example |
|---|---|---|
| **Claim** | One fact about the user | Name = Ravi, Email = ravi@teashop.com |
| **ClaimsIdentity** | The claims plus **how** the user was checked (the scheme) | claims + `"Cookies"` |
| **ClaimsPrincipal** | The user: holds the identity | what your code reads as `User` |

In the below example, Ravi is built from three claims. An identity counts as **logged in** only when it has a scheme name: here, `"Cookies"`.

<p>Logged in: @user.Identity?.IsAuthenticated</p>
<p>Scheme: @user.Identity?.AuthenticationType</p>

<ul>
      @foreach (var claim in user.Claims)
      {
          <li>@claim.Type.Split('/').Last(): @claim.Value</li>
      }
</ul>

@code {
      private ClaimsPrincipal user = MakeUser();

      private static ClaimsPrincipal MakeUser()
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, "Ravi"),
              new(ClaimTypes.Email, "ravi@teashop.com"),
              new(ClaimTypes.Role, "Customer"),
          };

          // The second argument is the scheme. Without it, nobody is logged in.
          var identity = new ClaimsIdentity(claims, "Cookies");
          return new ClaimsPrincipal(identity);
      }
}
`,
  }}
/>

- Remove `, "Cookies"` and run it again: `Logged in` turns `False`.
- `ClaimTypes.Name` is a long, standard name (a web address). `Split('/').Last()` only shortens it for display.

This is how you turn on the cookie scheme in `Program.cs`, and how a login page makes the cookie with **`SignInAsync`**:

      {
          options.LoginPath = "/login";                    // where to send users who are not logged in
          options.ExpireTimeSpan = TimeSpan.FromDays(7);   // how long a login lasts
          options.SlidingExpiration = true;                // each visit extends it
      });

builder.Services.AddCascadingAuthenticationState();
`}
/>

      <button type="submit">Log in</button>

@code {
      [CascadingParameter]
      public HttpContext HttpContext { get; set; } = default!;

      [SupplyParameterFromForm]
      private LoginModel Input { get; set; } = new();

      private async Task LogIn()
      {
          // Check Input.Email and Input.Password against your users here (Identity does this for you)

          var claims = new List<Claim> { new(ClaimTypes.Name, Input.Email) };
          var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

          // Writes the encrypted login cookie into the response
          await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
              new ClaimsPrincipal(identity));

          HttpContext.Response.Redirect("/");
      }

      private class LoginModel
      {
          public string Email { get; set; } = "";
          public string Password { get; set; } = "";
      }
}
`}
/>

- The login page must be a **static** page (no `@rendermode`), like the forms in **Server Rendering**. A cookie can only be set on an HTTP response, and interactive clicks have none.
- `HttpContext.SignOutAsync(...)` deletes the cookie again: that is logout.

### ASP.NET Core Identity

Writing users, passwords and login pages yourself is a lot of careful work. **ASP.NET Core Identity** is the built-in **membership system** (everything about user accounts). It gives you:

- A **users table** in your database (with EF Core, see **Database Handling**).
- Safe **password storage**, account lockout after many wrong tries, email confirmation and two-factor login.
- Ready-made Blazor pages: **Register**, **Login**, **Logout**, **Manage account**.
- The **cookie scheme**, set up for you.

The easiest start is a new app with **Individual Accounts** (`-au Individual`):

The template adds these parts:

| Part | Its job |
|---|---|
| `Data/ApplicationUser.cs` | Your user class. It inherits `IdentityUser` (email, password hash, and more) |
| `Data/ApplicationDbContext.cs` | The EF Core database with the Identity tables |
| `Components/Account/Pages/` | Register, Login, Manage and the other account pages |
| `UserManager<ApplicationUser>` | Creates and finds users, checks passwords |
| `SignInManager<ApplicationUser>` | Logs users in and out (makes and deletes the cookie) |

And it registers Identity in `Program.cs`:

      {
          options.DefaultScheme = IdentityConstants.ApplicationScheme;
          options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
      })
      .AddIdentityCookies();

// The database for the users
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
      ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlite(connectionString));

// Identity itself: users, sign-in and tokens
builder.Services.AddIdentityCore<ApplicationUser>(options =>
          options.SignIn.RequireConfirmedAccount = true)
      .AddEntityFrameworkStores<ApplicationDbContext>()
      .AddSignInManager()
      .AddDefaultTokenProviders();

var app = builder.Build();
// ...
app.MapAdditionalIdentityEndpoints();   // the Logout endpoint and more
`}
/>

### Password Storage

- **Never store passwords as they are.** If the database is stolen, every password is known at once.
- Store a **hash** instead: a one-way scramble. You can turn a password into a hash, but not a hash back into the password.
- Add a **salt** first: a random value, different for every user. Then two users with the same password still get different hashes.
- To check a login, hash the typed password with the **same salt** and compare the two hashes.

<figure className="blz-fig">
<svg viewBox="0 0 640 175" role="img" aria-labelledby="fig-auth-hash">
  <title id="fig-auth-hash">The password chai123 and a random salt go into PBKDF2, which mixes them 100,000 times. Out comes a hash. The database stores only the salt and the hash, never the password.</title>
  <defs><marker id="fig-auth-hash-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="25" width="130" height="50" rx="10" />
  <text className="t m" x="75" y="55" textAnchor="middle" style={{ fontSize: 12 }}>"chai123"</text>
  <rect className="org" x="10" y="105" width="130" height="50" rx="10" />
  <text className="t m" x="75" y="128" textAnchor="middle" style={{ fontSize: 12 }}>salt</text>
  <text className="t" x="75" y="145" textAnchor="middle" style={{ fontSize: 10 }}>random bytes</text>
  <rect className="pur" x="215" y="55" width="160" height="70" rx="12" />
  <text className="t m" x="295" y="85" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>PBKDF2</text>
  <text className="t" x="295" y="104" textAnchor="middle" style={{ fontSize: 10 }}>mixes 100,000 times</text>
  <rect className="grn" x="450" y="40" width="180" height="100" rx="12" />
  <text className="t m" x="540" y="64" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Database stores</text>
  <text className="t" x="540" y="88" textAnchor="middle" style={{ fontSize: 11 }}>salt</text>
  <text className="t" x="540" y="106" textAnchor="middle" style={{ fontSize: 11 }}>hash: siP+kso5qxqX...</text>
  <text className="t" x="540" y="126" textAnchor="middle" style={{ fontSize: 10 }}>no password</text>
  <path className="line" d="M140 50 L211 80" markerEnd="url(#fig-auth-hash-a)" />
  <path className="line" d="M140 130 L211 100" markerEnd="url(#fig-auth-hash-a)" />
  <path className="line" d="M375 90 H446" markerEnd="url(#fig-auth-hash-a)" />
</svg>
<figcaption>Password plus salt goes in; only the salt and the hash are stored.</figcaption>
</figure>

- **PBKDF2** is a hashing method made **slow on purpose**, so an attacker cannot try billions of passwords quickly.
- Identity does all this for you: its `PasswordHasher` uses PBKDF2 with SHA-512 and 100,000 rounds, and stores the salt and hash together in the `PasswordHash` column.

In the below example, you hash a password the same way (with fewer rounds, to stay fast in the browser). Click **Hash it** twice and compare: same password, new salt, different hash. Then click **Check**.

<button @onclick="Hash">Hash it</button>
<button @onclick="Check">Check "chai123"</button>

<p>Salt: @Convert.ToBase64String(salt)</p>
<p>Hash: @Convert.ToBase64String(hash)</p>
<p>@message</p>

@code {
      private string password = "chai123";
      private byte[] salt = Array.Empty<byte>();
      private byte[] hash = Array.Empty<byte>();
      private string message = "";

      private void Hash()
      {
          salt = RandomNumberGenerator.GetBytes(16);   // a new random salt
          hash = MakeHash(password, salt);
          message = "Saved: the salt and the hash. Not the password.";
      }

      private void Check()
      {
          if (salt.Length == 0)
          {
              message = "Click Hash it first.";
              return;
          }
          var attempt = MakeHash("chai123", salt);      // same salt as before
          message = CryptographicOperations.FixedTimeEquals(attempt, hash)
              ? "Correct password"
              : "Wrong password";
      }

      private static byte[] MakeHash(string text, byte[] salt) =>
          Rfc2898DeriveBytes.Pbkdf2(text, salt, 10_000, HashAlgorithmName.SHA256, 32);
}
`,
  }}
/>

- Change the box to `tea999`, click **Hash it**, then **Check**: "Wrong password".
- `FixedTimeEquals` compares in the same time whether the hashes match early or late, so timing gives nothing away.

Do not write your own password code in a real app. Use Identity, which hashes, salts, checks and upgrades passwords for you.

### Register, Login, and Logout

These are the three steps every account goes through. In the Identity template:

<figure className="blz-fig">
<svg viewBox="0 0 640 220" role="img" aria-labelledby="fig-auth-steps">
  <title id="fig-auth-steps">Three rows. Register: the form calls UserManager.CreateAsync, which saves the user with a password hash in the database. Login: the form calls SignInManager.PasswordSignInAsync, which checks the hash and writes the login cookie. Logout: a form posts to Account/Logout, which calls SignInManager.SignOutAsync and deletes the cookie.</title>
  <defs><marker id="fig-auth-steps-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="15" width="120" height="50" rx="10" />
  <text className="t m" x="70" y="45" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Register</text>
  <rect className="pur" x="170" y="15" width="250" height="50" rx="10" />
  <text className="t m" x="295" y="45" textAnchor="middle" style={{ fontSize: 11 }}>UserManager.CreateAsync</text>
  <rect className="grn" x="460" y="15" width="170" height="50" rx="10" />
  <text className="t m" x="545" y="45" textAnchor="middle" style={{ fontSize: 11 }}>user + hash saved</text>
  <rect className="blu" x="10" y="85" width="120" height="50" rx="10" />
  <text className="t m" x="70" y="115" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Login</text>
  <rect className="pur" x="170" y="85" width="250" height="50" rx="10" />
  <text className="t m" x="295" y="115" textAnchor="middle" style={{ fontSize: 11 }}>SignInManager.PasswordSignInAsync</text>
  <rect className="grn" x="460" y="85" width="170" height="50" rx="10" />
  <text className="t m" x="545" y="115" textAnchor="middle" style={{ fontSize: 11 }}>cookie written</text>
  <rect className="blu" x="10" y="155" width="120" height="50" rx="10" />
  <text className="t m" x="70" y="185" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Logout</text>
  <rect className="pur" x="170" y="155" width="250" height="50" rx="10" />
  <text className="t m" x="295" y="185" textAnchor="middle" style={{ fontSize: 11 }}>SignInManager.SignOutAsync</text>
  <rect className="org" x="460" y="155" width="170" height="50" rx="10" />
  <text className="t m" x="545" y="185" textAnchor="middle" style={{ fontSize: 11 }}>cookie deleted</text>
  <path className="line" d="M130 40 H166" markerEnd="url(#fig-auth-steps-a)" />
  <path className="line" d="M420 40 H456" markerEnd="url(#fig-auth-steps-a)" />
  <path className="line" d="M130 110 H166" markerEnd="url(#fig-auth-steps-a)" />
  <path className="line" d="M420 110 H456" markerEnd="url(#fig-auth-steps-a)" />
  <path className="line" d="M130 180 H166" markerEnd="url(#fig-auth-steps-a)" />
  <path className="line" d="M420 180 H456" markerEnd="url(#fig-auth-steps-a)" />
</svg>
<figcaption>Register saves the user. Login writes the cookie. Logout deletes it.</figcaption>
</figure>

The key lines from the template's pages:

      <button type="submit">Logout</button>
</form>
`}
/>

- `RememberMe` decides whether the cookie has an end date (it survives a browser restart) or is a session cookie.
- Logout is a **form that posts** to `Account/Logout`. That endpoint calls `SignInManager.SignOutAsync()`, which deletes the cookie. `<AntiforgeryToken />` stops other sites from logging your users out.

## Authentication State

The login cookie lives on the server side of the request. Your **components** need an easy way to ask "who is the user?". In Blazor, that is the **authentication state**.

### AuthenticationStateProvider

- **`AuthenticationStateProvider`** is the service that answers "who is the user?".
- Its method **`GetAuthenticationStateAsync()`** returns an **`AuthenticationState`**. Its **`User`** property is the `ClaimsPrincipal` you met above.
- When the user changes (login, logout), the provider calls **`NotifyAuthenticationStateChanged`**, so the components can update.
- In the Identity template, the provider is `IdentityRevalidatingAuthenticationStateProvider`. It reads the user from the login cookie and checks every 30 minutes that the account still exists.

In the code boxes there is no login cookie. So `TeaShopAuthStateProvider` is a pretend provider: its `LogIn` and `LogOut` methods change the user directly. A real app registers its provider in `Program.cs`. The code boxes do that for you:

In the below example, the page injects the provider and asks it who the user is. Click **Who am I?**, then log in and ask again.

<button @onclick="LogOut">Log out</button>
<button @onclick="Check">Who am I?</button>

<p>@message</p>

@code {
      private string message = "";

      private async Task Check()
      {
          AuthenticationState state = await AuthProvider.GetAuthenticationStateAsync();
          var user = state.User;
          message = user.Identity?.IsAuthenticated == true
              ? "Logged in as " + user.Identity.Name
              : "Not logged in";
      }

      // Only the pretend provider has LogIn and LogOut.
      // In a real app, the Login and Logout pages do this.
      private async Task LogIn()
      {
          ((TeaShopAuthStateProvider)AuthProvider).LogIn("Ravi");
          await Check();
      }

      private async Task LogOut()
      {
          ((TeaShopAuthStateProvider)AuthProvider).LogOut();
          await Check();
      }
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider. In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name)
      {
          var claims = new[] { new Claim(ClaimTypes.Name, name) };
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

### Cascading Authentication State

- Asking the provider in every component is repetitive, and the page does not update by itself after login.
- **Cascading authentication state** hands the state down to **every** component, like the cascading values in **Components**.
- Turn it on once in `Program.cs` with **`builder.Services.AddCascadingAuthenticationState();`** (the Identity template already has it). You can also wrap a part of the page in **`<CascadingAuthenticationState>`**.
- A component receives it as a **`[CascadingParameter] Task<AuthenticationState>`**. It is a `Task`, so you `await` it.
- When the provider says the user changed, every component gets the new state and renders again.

<figure className="blz-fig">
<svg viewBox="0 0 640 235" role="img" aria-labelledby="fig-auth-cascade">
  <title id="fig-auth-cascade">Animation: the AuthenticationStateProvider at the top feeds CascadingAuthenticationState. From there, the Task of AuthenticationState flows down to three components, NavMenu, OrdersPage and UserBadge, which each receive it as a cascading parameter.</title>
  <defs><marker id="fig-auth-cascade-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="220" y="10" width="200" height="44" rx="10" />
  <text className="t m" x="320" y="37" textAnchor="middle" style={{ fontSize: 11, fontWeight: 700 }}>AuthenticationStateProvider</text>
  <rect className="org" x="200" y="84" width="240" height="44" rx="10" />
  <text className="t m" x="320" y="111" textAnchor="middle" style={{ fontSize: 11, fontWeight: 700 }}>CascadingAuthenticationState</text>
  <rect className="blu" x="20" y="178" width="160" height="44" rx="10" />
  <text className="t m" x="100" y="205" textAnchor="middle" style={{ fontSize: 11 }}>NavMenu</text>
  <rect className="blu" x="240" y="178" width="160" height="44" rx="10" />
  <text className="t m" x="320" y="205" textAnchor="middle" style={{ fontSize: 11 }}>OrdersPage</text>
  <rect className="blu" x="460" y="178" width="160" height="44" rx="10" />
  <text className="t m" x="540" y="205" textAnchor="middle" style={{ fontSize: 11 }}>UserBadge</text>
  <path className="line" d="M320 54 V80" markerEnd="url(#fig-auth-cascade-a)" />
  <path className="line" d="M260 128 L104 174" markerEnd="url(#fig-auth-cascade-a)" />
  <path className="line" d="M320 128 V174" markerEnd="url(#fig-auth-cascade-a)" />
  <path className="line" d="M380 128 L536 174" markerEnd="url(#fig-auth-cascade-a)" />
  <text className="t" x="320" y="160" textAnchor="middle" style={{ fontSize: 10 }}>Task&lt;AuthenticationState&gt;</text>
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="320;320;100" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
    <animate attributeName="cy" values="54;128;178" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
  </circle>
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="320;320;320" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
    <animate attributeName="cy" values="54;128;178" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
  </circle>
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="320;320;540" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
    <animate attributeName="cy" values="54;128;178" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>One provider, one cascade, and every component below it knows the user.</figcaption>
</figure>

In the below example, `UserBadge` has no buttons and no injected service. It only receives the cascading state, yet it updates when you log in or out.

<button @onclick="() => Provider.LogOut()">Log out</button>

@code {
      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Components/Pages/UserBadge.razor": `@using Microsoft.AspNetCore.Components.Authorization

<p><b>@text</b></p>

@code {
      [CascadingParameter]
      private Task<AuthenticationState>? AuthState { get; set; }

      private string text = "";

      protected override async Task OnParametersSetAsync()
      {
          if (AuthState is null) return;

          var state = await AuthState;
          text = state.User.Identity?.IsAuthenticated == true
              ? "Hello, " + state.User.Identity.Name + "!"
              : "Hello, guest!";
      }
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider. In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name)
      {
          var claims = new[] { new Claim(ClaimTypes.Name, name) };
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- `OnParametersSetAsync` runs again each time the cascading value changes, so the text stays up to date.
- With `AddCascadingAuthenticationState()` in `Program.cs`, you do not need the `<CascadingAuthenticationState>` tag. The code boxes use the tag because they have no `Program.cs` of their own.

Showing or hiding things by login state only changes the **screen**. Real protection, such as blocking a page or an API for strangers, is **authorization**: the next lesson.

### Accessing the Current User (ClaimsPrincipal)

Once you have the `AuthenticationState`, its `User` is a `ClaimsPrincipal`. These are the members you use most:

| Code | Gives you |
|---|---|
| `User.Identity?.IsAuthenticated` | `true` when someone is logged in |
| `User.Identity?.Name` | The name claim, for example `Ravi` |
| `User.FindFirst(ClaimTypes.Email)?.Value` | The value of one claim, or null |
| `User.IsInRole("Staff")` | `true` when the user has that role claim |
| `User.Claims` | All claims, to loop over |

In the below example, the provider logs in a user with a name, an email and a role. `UserCard` reads them from the cascading state. Try both buttons.

<button @onclick='() => Provider.LogIn("Meena", "meena@teashop.com", "Staff")'>Meena (staff)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

@code {
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Components/Pages/UserCard.razor": `@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization

@if (user?.Identity?.IsAuthenticated == true)
{
      <p>Name: @user.Identity.Name</p>
      <p>Email: @user.FindFirst(ClaimTypes.Email)?.Value</p>
      <p>Staff: @user.IsInRole("Staff")</p>
      <p>Claims: @user.Claims.Count()</p>
}
else
{
      <p>Nobody is logged in.</p>
}

@code {
      [CascadingParameter]
      private Task<AuthenticationState>? AuthState { get; set; }

      private ClaimsPrincipal? user;

      protected override async Task OnParametersSetAsync()
      {
          if (AuthState is not null)
          {
              user = (await AuthState).User;
          }
      }
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider. In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string email, string role)
      {
          var claims = new[]
          {
              new Claim(ClaimTypes.Name, name),
              new Claim(ClaimTypes.Email, email),
              new Claim(ClaimTypes.Role, role),
          };
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- Meena has the role claim `Staff`, so `IsInRole("Staff")` is `True`. The next lesson uses roles like this to decide who may open which page.
- In C# code outside components (for example in an API endpoint), the same user is `HttpContext.User`.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Saving passwords as plain text, or with a fast hash like SHA-256 only | A hash is a hash | Use Identity's `PasswordHasher` (PBKDF2 with salt) | Stolen databases reveal passwords |
| A login cookie without HttpOnly or Secure | Default options are fine everywhere | Keep `HttpOnly`, `Secure` and `SameSite` on | Scripts or the network can steal the login |
| `new ClaimsIdentity(claims)` with no scheme | Having claims means logged in | Pass the scheme: `new ClaimsIdentity(claims, "Cookies")` | `IsAuthenticated` is false |
| Calling `SignInAsync` from an interactive component | Any button can set a cookie | Log in from a static page or an endpoint | "Headers are read-only" or no cookie at all |
| Using `HttpContext` in interactive components | It is always there | Use the authentication state instead | `HttpContext` is null, so the code crashes |
| Forgetting `AddCascadingAuthenticationState()` | Components find the user by themselves | Add it in `Program.cs` (or wrap with `<CascadingAuthenticationState>`) | The cascading `Task<AuthenticationState>` is null |

</div>

## Check Yourself

## Exercises

## What to Remember

- **Authentication** finds out who the user is. After login, a **cookie** carries the proof with every request.
- A cookie is named text the browser keeps and sends back. Set it with `Response.Cookies.Append`, read it with `Request.Cookies[...]`, delete it with `Response.Cookies.Delete`.
- Protect cookies with **HttpOnly**, **Secure**, **SameSite** and an expiry.
- The **cookie scheme** writes an encrypted login cookie with `SignInAsync` and removes it with `SignOutAsync`. The user is a `ClaimsPrincipal` made of **claims**.
- **ASP.NET Core Identity** gives you users, safe password hashing (salt + PBKDF2) and the Register, Login and Logout pages. Start with `dotnet new blazor -au Individual`.
- Components get the user from **`AuthenticationStateProvider`**, or better, from the cascading **`Task<AuthenticationState>`** (`AddCascadingAuthenticationState()`).
- Read the user with `Identity.IsAuthenticated`, `Identity.Name`, `FindFirst(...)` and `IsInRole(...)`.

Next: **Authorization**
