JWT Authentication in ASP.NET Core: The Production Guide

Short-lived access tokens, rotating refresh tokens, role-based policies — and the defaults that quietly break your API.

R M Shahidul Islam Shahed · 6 min read

JWT authentication is the most common way to secure an ASP.NET Core Web API, and one of the most often misconfigured. This guide builds it the way it runs in production on .NET 10: short-lived access tokens, rotating refresh tokens stored as hashes, role-based policies, and the settings whose defaults catch people out.

What we are building

A Web API with three moving parts:

  • POST /auth/login checks credentials and returns an access token and a refresh token.
  • POST /auth/refresh swaps a valid refresh token for a new pair and retires the old one.
  • Protected endpoints guarded by RequireAuthorization() and named policies.

Rule of thumb: access tokens live minutes, refresh tokens live days, and both can be revoked.

The access token is a signed JWT the API validates on every request without a database call. The refresh token is a random string the API looks up, so it can be revoked at any time. That split is the whole design: fast checks for the common path, a database check only when a session is extended.

Install the packages

On top of the Web API template you need the JWT bearer handler. It brings Microsoft.IdentityModel.JsonWebTokens with it, which is the token library ASP.NET Core itself uses since .NET 8.

bash
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Keep the settings in one options class

Bind the settings once, validate them on start, and inject IOptions<JwtOptions> wherever they are needed. A missing or short key then fails at startup, not on the first login.

csharp
public sealed class JwtOptions
{
    public const string Section = "Jwt";

    [Required] public string Issuer { get; init; } = "";
    [Required] public string Audience { get; init; } = "";

    // 32 bytes = 256 bits, the minimum for HMAC-SHA256.
    [Required, MinLength(32)] public string Key { get; init; } = "";

    [Range(1, 60)] public int AccessTokenMinutes { get; init; } = 10;
    [Range(1, 90)] public int RefreshTokenDays { get; init; } = 14;
}
csharp
builder.Services.AddOptions<JwtOptions>()
    .BindConfiguration(JwtOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart();

Keep the key out of source control: User Secrets in development, an environment variable or a vault in production.

Configure the JWT bearer handler

csharp
var jwt = builder.Configuration.GetSection(JwtOptions.Section).Get<JwtOptions>()!;

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.MapInboundClaims = false; // keep "sub", "role" as they are in the token
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwt.Issuer,
            ValidateAudience = true,
            ValidAudience = jwt.Audience,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)),
            ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
            RoleClaimType = "role",
            NameClaimType = "sub",
            ClockSkew = TimeSpan.FromSeconds(30),
        };
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("AdminOnly", p => p.RequireRole("Admin"));

The default ClockSkew is 5 minutes. If your access token lives 10 minutes, it is really valid for 15. Set it explicitly.

Two more lines worth their place:

  • ValidAlgorithms pins the algorithm, so a token signed some other way is rejected even if the key would match.
  • MapInboundClaims = false stops the handler renaming sub to a long XML-namespace claim type. Your code and your tokens then use the same names.

Issue the access token

Keep token creation in one small service so it can be unit-tested on its own.

csharp
public sealed class TokenService(IOptions<JwtOptions> options, TimeProvider time)
{
    private readonly JsonWebTokenHandler _handler = new();

    public string CreateAccessToken(string userId, string email, IEnumerable<string> roles)
    {
        var o = options.Value;
        var claims = new Dictionary<string, object>
        {
            [JwtRegisteredClaimNames.Sub] = userId,
            [JwtRegisteredClaimNames.Email] = email,
            [JwtRegisteredClaimNames.Jti] = Guid.NewGuid().ToString("N"),
            ["role"] = roles.ToArray(),
        };

        var now = time.GetUtcNow().UtcDateTime;
        return _handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = o.Issuer,
            Audience = o.Audience,
            Claims = claims,
            IssuedAt = now,
            NotBefore = now,
            Expires = now.AddMinutes(o.AccessTokenMinutes),
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(o.Key)), SecurityAlgorithms.HmacSha256),
        });
    }
}

TimeProvider instead of DateTime.UtcNow means a test can move the clock and check expiry without waiting.

Put only what the API needs in the token. It is signed, not encrypted: anyone holding it can read every claim.

Store refresh tokens as hashes

A refresh token is a bearer secret, like a password. Store a SHA-256 hash, never the token itself, so a database leak doesn't hand out live sessions.

csharp
public sealed class RefreshToken
{
    public long Id { get; set; }
    public string UserId { get; set; } = "";
    public byte[] TokenHash { get; set; } = [];
    public Guid FamilyId { get; set; }            // all tokens from one login
    public DateTime ExpiresAtUtc { get; set; }
    public DateTime? UsedAtUtc { get; set; }
    public DateTime? RevokedAtUtc { get; set; }
}
csharp
static string NewRefreshToken() =>
    Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));

static byte[] Hash(string token) =>
    SHA256.HashData(Encoding.UTF8.GetBytes(token));

Add a unique index on TokenHash so lookups stay fast as the table grows.

Rotate on every use and detect replays

Every refresh issues a new refresh token and marks the old one used. If a used token ever comes back, someone has a copy: revoke the whole family, which signs that device out.

csharp
public async Task<TokenPair?> RotateAsync(string presented, CancellationToken ct)
{
    var hash = Hash(presented);
    var current = await db.RefreshTokens.SingleOrDefaultAsync(t => t.TokenHash == hash, ct);
    var now = time.GetUtcNow().UtcDateTime;

    if (current is null || current.RevokedAtUtc is not null || current.ExpiresAtUtc <= now)
    {
        return null;
    }

    if (current.UsedAtUtc is not null)
    {
        // Replay: an old token was used again. End every session from this login.
        await db.RefreshTokens
            .Where(t => t.FamilyId == current.FamilyId && t.RevokedAtUtc == null)
            .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAtUtc, now), ct);
        return null;
    }

    current.UsedAtUtc = now;
    var next = NewRefreshToken();
    db.RefreshTokens.Add(new RefreshToken
    {
        UserId = current.UserId,
        TokenHash = Hash(next),
        FamilyId = current.FamilyId,
        ExpiresAtUtc = now.AddDays(options.Value.RefreshTokenDays),
    });
    await db.SaveChangesAsync(ct);

    var user = await users.FindByIdAsync(current.UserId);
    var roles = await users.GetRolesAsync(user!);
    return new TokenPair(tokens.CreateAccessToken(user!.Id, user.Email!, roles), next);
}

Two refresh calls racing each other with the same token will look like a replay. If your client can do that (two tabs, a retry), allow a grace period of a few seconds on UsedAtUtc before treating it as one.

Wire up the endpoints

csharp
var auth = app.MapGroup("/auth").AllowAnonymous();

auth.MapPost("/login", async (LoginRequest req, AuthService service, CancellationToken ct) =>
    await service.LoginAsync(req, ct) is { } pair ? Results.Ok(pair) : Results.Unauthorized());

auth.MapPost("/refresh", async (RefreshRequest req, AuthService service, CancellationToken ct) =>
    await service.RotateAsync(req.RefreshToken, ct) is { } pair ? Results.Ok(pair) : Results.Unauthorized());

app.MapGet("/api/orders", GetOrders).RequireAuthorization();
app.MapDelete("/api/users/{id}", DeleteUser).RequireAuthorization("AdminOnly");

Rate-limit /auth/login and /auth/refresh with the built-in rate limiting middleware. A few attempts per minute per IP is plenty for real users and slows down password guessing.

Sign out properly

"Signing out" a JWT client means revoking its refresh token family. The access token still works until it expires, which is why its lifetime stays short. If you need instant revocation for one user (a fired employee, a stolen laptop), keep a small deny list of jti values or a per-user "tokens valid after" timestamp and check it in OnTokenValidated.

Production checklist

Setting Recommended
Access token lifetime 5–15 minutes
Refresh token lifetime 7–30 days, rotated on every use
Refresh token storage SHA-256 hash, unique index
Signing key 256 bits or more, from a vault
Algorithm Pinned with ValidAlgorithms
ClockSkew 30 seconds
Login and refresh Rate-limited
HTTPS Required everywhere

Wrapping up

JWT in ASP.NET Core is a few lines of setup and a handful of decisions. Short access tokens, hashed and rotated refresh tokens, a pinned algorithm and an explicit clock skew give you an API that is secure by default and straightforward to reason about. The next step is adding ASP.NET Core Identity with passkeys or two-factor sign-in on top of this setup.

Keep reading

All articles →
C#

C# 14 Features You'll Use Every Day

Extension members, the field keyword, null-conditional assignment and more — with before/after code.

1 min read
EF Core & Databases

12 EF Core Performance Tips That Actually Matter

AsNoTracking, compiled queries, split queries and bulk updates — measured on a real ERP database, not a toy sample.

1 min read
AI in .NET & AI Coding Tools

My AI-Native .NET Workflow with Claude Code

How I use coding agents to scaffold features, write tests and review PRs on a production ASP.NET Core codebase.

1 min read