SkillPilotAI

JWT login and refresh tokens

A JWT lets an API authenticate every request without a server session, but only if the server validates it: signature, issuer, audience and expiry. This note covers AddJwtBearer, issuing tokens with JsonWebTokenHandler, refresh token rotation, signing keys and API keys for server-to-server calls.

58.1 The problem: the token is only decoded

  • Riya's JWT has role = customer, so /admin returns 403.
  • The endpoint uses new JsonWebToken(raw): it only decodes (reads) the token.
  • A tamper script changes role to admin without touching the signature, and the server says Hello admin.
C#
app.MapGet("/admin", (HttpRequest req) =>{    var raw = req.Headers.Authorization        .ToString().Replace("Bearer ", "");    var token = new JsonWebToken(raw);    var role = token.GetClaim("role").Value;    return role == "admin"        ? Results.Ok($"Hello admin {token.Subject}")        : Results.StatusCode(403);});
Output
$ dotnet run tamper.cs $TOKEN{"aud":"shop-api",...,"sub":"riya@shop.in","role":"customer",...}{"aud":"shop-api",...,"sub":"riya@shop.in","role":"admin",...}eyJhbGciOiJIUzI1NiIs...$ curl -i localhost:5058/admin \  -H "Authorization: Bearer $FAKE"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8"Hello admin riya@shop.in"
How we became admin
  1. 1.Only decoded: the payload is base64url, read not verified

  2. 2.No signature check: anyone edits the role

  3. 3.No expiry / issuer check: old tokens still work

Needed: AddJwtBearer = validation on every request

58.2 Program.cs: AddJwtBearer

  • Add the Microsoft.AspNetCore.Authentication.JwtBearer package.
  • The Jwt section from configuration gives Key, Issuer and Audience; the key becomes a SymmetricSecurityKey.
  • MapInboundClaims = false keeps short claim names like sub and role.
  • TokenValidationParameters: ValidIssuer, ValidAudience, IssuerSigningKey; the lifetime check is on by default.
C#
var builder = WebApplication.CreateBuilder(args);var jwt = builder.Configuration.GetSection("Jwt");var key = new SymmetricSecurityKey(    Encoding.UTF8.GetBytes(jwt["Key"]!));builder.Services.AddAuthentication()    .AddJwtBearer(o =>    {        o.MapInboundClaims = false;        o.TokenValidationParameters = new()        {            ValidIssuer = jwt["Issuer"],            ValidAudience = jwt["Audience"],            IssuerSigningKey = key        };    });

58.3 Issuing the access token

  • A SecurityTokenDescriptor holds every detail: the same Issuer / Audience used by validation.
  • Claims: sub = user email, role = user role.
  • Expires in only 15 minutes; signed with the key + HmacSha256.
  • JsonWebTokenHandler.CreateToken returns the full signed JWT string.
C#
public string CreateAccessToken(AppUser user){    var descriptor = new SecurityTokenDescriptor    {        Issuer = jwt["Issuer"],        Audience = jwt["Audience"],        Subject = new ClaimsIdentity([            new Claim("sub", user.Email),            new Claim("role", user.Role)]),        Expires = DateTime.UtcNow.AddMinutes(15),        SigningCredentials = new(key,            SecurityAlgorithms.HmacSha256)    };    return handler.CreateToken(descriptor);}

58.4 Login + protected endpoint

  • /login checks the password with PasswordHasher and returns a token pair.
  • The response has accessToken, refreshToken and expiresIn = 900 seconds.
  • /orders uses RequireAuthorization and reads the email from the sub claim.
  • No token: 401 with WWW-Authenticate: Bearer.
C#
app.MapPost("/login", (LoginRequest r,    UserStore users, TokenService tokens) =>    users.Check(r.Email, r.Password) is { } user        ? Results.Ok(tokens.Issue(user))        : Results.Unauthorized()); app.MapPost("/refresh", (RefreshRequest r,    TokenService tokens) =>    tokens.Refresh(r.RefreshToken) is { } pair        ? Results.Ok(pair)        : Results.Unauthorized()); app.MapGet("/orders", (ClaimsPrincipal user) =>    $"Orders of {user.FindFirstValue("sub")}")    .RequireAuthorization();
Output
$ curl -i localhost:5058/login \  -H "Content-Type: application/json" \  -d '{"email":"riya@shop.in","password":"Riya@1234"}'HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "accessToken": "eyJhbGciOiJIUzI1NiIs...",  "refreshToken": "VuOmCF9McJTf8HddH8nQ...",  "expiresIn": 900 }$ curl -i localhost:5058/orders \  -H "Authorization: Bearer $TOKEN"HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Orders of riya@shop.in$ curl -i localhost:5058/ordersHTTP/1.1 401 UnauthorizedContent-Length: 0WWW-Authenticate: Bearer
The JWT login flow
  1. 1.Login: 15-minute access token + refresh token

  2. 2.Every request: Authorization: Bearer <access token>

  3. 3.AddJwtBearer checks signature, issuer, audience, expiry -> User

  4. 4.Expired: POST /refresh -> new pair

No session on the server; every request is verified by the token

58.5 Checkpoint: an edited token

  • The same role=admin token now gets 401: once the payload changes the signature no longer matches.
  • Without the secret key nobody can create a valid signature.
Output
$ curl -i localhost:5058/orders \  -H "Authorization: Bearer $FAKE"HTTP/1.1 401 UnauthorizedContent-Length: 0WWW-Authenticate: Bearer error="invalid_token",  error_description="The signature key was not found"

58.6 Refresh token rotation

  • The refresh token is 32 random bytes, stored with a 7-day expiry.
  • Refresh uses TryRemove: the old token is deleted, so every refresh is a rotation.
  • Reusing the old refresh token gives 401 because it is already gone.
  • In a real database store only the refresh token's hash.
C#
public TokenPair Issue(AppUser user){    var refresh = Convert.ToBase64String(        RandomNumberGenerator.GetBytes(32));    refreshTokens[refresh] = new(user,        DateTime.UtcNow.AddDays(7));    return new(CreateAccessToken(user),        refresh, 900);} public TokenPair? Refresh(string token) =>    refreshTokens.TryRemove(token, out var e)    && e.Expires > DateTime.UtcNow        ? Issue(e.User) : null;
Output
$ curl -i localhost:5058/refresh \  -H "Content-Type: application/json" \  -d '{"refreshToken":"VuOmCF9McJTf8HddH8nQ..."}'HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "accessToken": "eyJhbGciOiJIUzI1NiIs...",  "refreshToken": "68lottHE56sDabyxkd5e...",  "expiresIn": 900 }# the same old refresh token again$ curl -i localhost:5058/refresh \  -H "Content-Type: application/json" \  -d '{"refreshToken":"VuOmCF9McJTf8HddH8nQ..."}'HTTP/1.1 401 UnauthorizedContent-Length: 0
PointAccess tokenRefresh token
FormatSigned JWT (sub, role, exp)32 random bytes, opaque
Lifetime15 minutes (expiresIn 900)7 days
Sent toEvery API call (Authorization: Bearer)Only POST /refresh
Checked byAddJwtBearer, no DB lookupServer store (hash in DB)
After useReused until expiryRotated: removed, new pair issued

58.7 API key: server to server

  • Useful when a partner server, not a user, calls your API.
  • An endpoint filter reads X-Api-Key and compares it with the key from configuration.
  • CryptographicOperations.FixedTimeEquals so the comparison time does not leak the key.
  • An API key identifies an app, not a user: it is not a replacement for user login.
C#
app.MapGet("/partner/stock", () =>        new { Sku = "MIXER-01", Stock = 42 })    .AddEndpointFilter(async (ctx, next) =>    {        var sent = Encoding.UTF8.GetBytes(            ctx.HttpContext.Request                .Headers["X-Api-Key"].ToString());        var real = Encoding.UTF8.GetBytes(            app.Configuration["ApiKeys:Partner"]!);        return CryptographicOperations            .FixedTimeEquals(sent, real)            ? await next(ctx)            : Results.Unauthorized();    });
Output
$ curl -i localhost:5058/partner/stockHTTP/1.1 401 UnauthorizedContent-Length: 0$ curl -i localhost:5058/partner/stock \  -H "X-Api-Key: fake-partner-key-123"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"sku":"MIXER-01","stock":42}

58.8 Common mistakes

  • A short hard-coded key ("secret123"): CreateToken throws IDX10653 (HS256 needs at least 128 bits), and anyone reading the repo could sign tokens.
  • Fix: a long random key in user-secrets; in production an environment variable (Jwt__Key) or Key Vault.
  • Assuming a token is rejected right at expiry: ClockSkew defaults to 5 minutes, so a token expired 2 minutes ago still gets 200. Set ClockSkew to zero or 30 seconds and it gets 401 (token expired).
  • Decoding a token and trusting it instead of validating it.
Terminal
dotnet user-secrets initdotnet user-secrets set "Jwt:Key" \  "$(openssl rand -base64 48)"# Program.cs: jwt["Key"] from config# production: environment variable# Jwt__Key or Key Vault

58.9 Rules for JWT

  1. Don't write token validation yourself: AddJwtBearer with issuer, audience and lifetime checks on.
  2. Short-lived access token (15 minutes) and a small ClockSkew.
  3. Refresh token: random, rotated on every use, only its hash in the database.
  4. Signing key: at least 32 random bytes, in secrets, not in code.
  5. API keys only for server-to-server calls.

58.10 Interview tips

  • Decoding is not validation: AddJwtBearer validates signature, issuer, audience and expiry on every request.
  • At login JsonWebTokenHandler issues a 15-minute access token plus a random refresh token.
  • Refresh removes the old token and returns a new pair (rotation); the signing key lives in a secrets store.
  • Mention ClockSkew (5-minute default) and API keys with a fixed-time compare for partner servers.