Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 52 ยท Authentication and Authorization

Cookie and JWT Bearer Authentication

Learn how cookie authentication and JWT bearer tokens work in ASP.NET Core, and build and validate an HMAC-signed token by hand to see what happens inside.

Two credentials dominate web applications. A cookie is what a browser-based site uses: the server remembers you were signed in and the browser sends the proof back automatically. A JWT bearer token is what most APIs use: the client holds a signed token and sends it in the Authorization header on every call. In Authentication Concepts you saw that both are just schemes with handlers. This lesson opens them up.

You will run real cookie authentication, then build a JSON Web Token from scratch with nothing but the base class library so that "signed token" stops being magic. The official JWT bearer handler lives in a NuGet package that the single-file runner here does not have, so for that part we use a faithful hand-written stand-in and show the real configuration as read-only code.

With cookie authentication the server does the remembering:

  1. The user submits credentials to a login endpoint.
  2. Your code verifies them and calls HttpContext.SignInAsync(principal).
  3. The cookie handler serializes the principal (its claims), encrypts and signs the result with the Data Protection system, and sends it as a Set-Cookie header.
  4. On every later request the browser sends the cookie back, and the handler decrypts it and rebuilds the ClaimsPrincipal.
sequenceDiagram
    participant B as Browser
    participant S as ASP.NET Core
    B->>S: POST /login (credentials)
    S->>S: verify, SignInAsync(principal)
    S-->>B: 200 + Set-Cookie (encrypted ticket)
    B->>S: GET /me + Cookie
    S->>S: decrypt cookie, rebuild User
    S-->>B: 200 (your data)

The cookie carries the whole encrypted ticket; the server stores nothing per session by default.

The cookie is not a session id pointing at server memory: it is the identity, protected so it cannot be read or forged without the server's keys. The consequences are useful to know. Keep claims small (cookies have a size limit of about 4 KB). Changing a user's role does not affect an already issued cookie until it expires or is validated again. And the same keys must be available to every server in a farm, which is what Data Protection is for (Web Security Essentials returns to it).

C# Cookie authentication, end to end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The two event handlers matter. By default an unauthenticated browser request to a cookie-protected page is redirected to /Account/Login, and a forbidden one to /Account/AccessDenied. That is right for web pages and wrong for an API, which should simply answer 401 or 403, so the example replaces both.

Three cookie flags deserve your attention in any real site: HttpOnly (JavaScript cannot read the cookie, which blunts token theft through XSS), Secure (only send over HTTPS: set SecurePolicy = CookieSecurePolicy.Always in production) and SameSite (Lax or Strict stops most cross-site request forgery; see Web Security Essentials).

What a JWT is

A JSON Web Token (JWT, pronounced "jot") is a compact string with three Base64Url-encoded parts separated by dots:

TEXT
header.payload.signature
  • The header says how the token is signed: {"alg":"HS256","typ":"JWT"}.
  • The payload holds the claims as JSON: who the token is about (sub), who issued it (iss), who it is for (aud), when it expires (exp, in seconds since 1970), plus anything you add such as role.
  • The signature is a cryptographic proof computed over header.payload with a secret (HMAC, "HS256") or a private key (RSA/ECDSA).

A JWT is signed, not encrypted. Anybody who holds the token can decode and read the payload with no key at all. Never put passwords, personal data or anything secret in it. The signature only guarantees that the contents were not changed and who made them.

Unlike a cookie, the server needs to remember nothing: a service that knows the signing key can validate a token alone. That is why JWTs suit APIs called by mobile apps, single-page apps and other services. The price is that a token cannot easily be taken back before it expires, so keep lifetimes short (minutes) and pair them with a refresh mechanism.

Building and validating a token by hand

Everything needed is in the base class library: HMACSHA256 for the signature, Base64Url (in System.Buffers.Text, since .NET 9) for the encoding and System.Text.Json for the payload. Run it and watch the three parts appear, then see why changing a single byte invalidates the token.

C# A JWT built by hand with HMAC-SHA256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

CryptographicOperations.FixedTimeEquals compares two byte arrays in constant time, so an attacker cannot learn how many leading bytes were right by measuring response times. Use it for any secret comparison.

A signature check is only the first of several checks. A complete validator also verifies:

  • the algorithm is the one you expect (never trust the header blindly: the infamous alg: none attack sends an unsigned token and hopes the server obeys);
  • the issuer (iss) and audience (aud) match your service, so a token minted for another system is rejected;
  • the token is within its lifetime: not past exp, and not before nbf ("not before") if present, allowing a small clock skew.

In the official handler these rules are TokenValidationParameters: ValidateIssuer, ValidateAudience, ValidateLifetime, ValidateIssuerSigningKey, IssuerSigningKey, ValidAlgorithms and ClockSkew.

A bearer handler (stand-in) in a real pipeline

The next program wires the same idea into ASP.NET Core with the pieces from the previous lesson: a /token endpoint issues a token and a custom scheme named Bearer validates the Authorization: Bearer ... header. It is deliberately small, so it checks the algorithm, signature, issuer, audience and expiry, but it is a teaching stand-in, not a replacement for the library.

C# Issuing and validating bearer tokens in a web app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice what the client sees in every failure: just 401 and a WWW-Authenticate: Bearer header. The reason (expired, bad signature) stays in server logs. Telling an attacker exactly which check failed helps them. Clients that need to refresh simply react to any 401 by fetching a new token.

The real thing: JwtBearer

In a normal project you add the Microsoft.AspNetCore.Authentication.JwtBearer package and the whole stand-in above becomes configuration. This code is read-only here because the package is not available to the runner:

C#
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "https://auth.example.com",
            ValidateAudience = true,
            ValidAudience = "my-api",
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(30),
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
        };
    });

Read the signing key from configuration or a secret store, never from source code (Environments and Secrets covers this). When your tokens come from an external identity provider (Microsoft Entra ID, Auth0, Keycloak), the handler can instead fetch the provider's public keys from its discovery document using options.Authority, so your API needs no shared secret at all.

Cookies or tokens?

Cookie JWT bearer
Typical client Browser pages served by the same site Mobile apps, SPAs on another origin, services
Who sends it The browser, automatically Your code, explicitly, in a header
Main risk CSRF (browser sends it automatically) Theft from storage; no easy revocation
Revocation Easy with server-side checks Hard until expiry; keep lifetimes short
Good default for Server-rendered sites and Blazor Server Public and machine-to-machine APIs

A common shape is a site with cookies for its own pages and a bearer scheme for /api, selected per endpoint. Authorization: Roles, Policies and Handlers shows how to decide what a signed-in caller may do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is stored inside an ASP.NET Core authentication cookie by default?

    The cookie handler serializes the principal into a ticket and protects it with Data Protection (encrypt and sign). The server keeps no per-session state unless you add a session store.
  2. 2. Why is it a mistake to put a user's phone number into a JWT payload?

    Base64Url is an encoding, not encryption. Anyone can decode the header and payload; the signature only proves the content was not modified.
  3. 3. A token's signature is valid, but its exp claim is in the past. What should a validator do?

    Signature, algorithm, issuer, audience and lifetime are all separate checks, and every one must pass.
  4. 4. Why compare signatures with CryptographicOperations.FixedTimeEquals instead of ==?

    A normal comparison stops at the first differing byte; an attacker who can measure response times could recover a valid signature byte by byte. Constant-time comparison closes that side channel.
  5. 5. What should an API's cookie scheme do for an unauthenticated request, instead of the default?

    The default redirects to /Account/Login, which suits web pages. API clients expect status codes, so OnRedirectToLogin and OnRedirectToAccessDenied are replaced.

Summary

  • Cookie authentication stores an encrypted, signed ticket in a cookie; the browser replays it and the server rebuilds the principal. Use HttpOnly, Secure and SameSite.
  • APIs should return 401/403 instead of redirects, by overriding the cookie events.
  • A JWT is header.payload.signature: signed, not encrypted, so keep secrets out of it.
  • A full validation checks the algorithm, signature (in constant time), issuer, audience and lifetime.
  • The real AddJwtBearer handler expresses these checks as TokenValidationParameters; keep keys in configuration or an identity provider.
  • Pick cookies for browser sites and bearer tokens for APIs and other clients; short lifetimes make tokens safer.

Next: Authorization: Roles, Policies and Handlers