0Pricing
C# Academy · Lesson

Configuring JWT Bearer Authentication

Wire up token validation in the pipeline.

Configuring JWT Bearer Authentication is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The JWT Bearer Handler

ASP.NET Core validates incoming JWTs using the JWT Bearer authentication handler from the Microsoft.AspNetCore.Authentication.JwtBearer package.

It reads the token from the Authorization: Bearer ... header, validates it, and builds a ClaimsPrincipal.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

AddAuthentication

Registration starts with AddAuthentication. You set the default scheme so the framework knows which handler to use when no scheme is specified.

JwtBearerDefaults.AuthenticationScheme is the string "Bearer".

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer();

AddJwtBearer Options

The AddJwtBearer overload takes an options delegate where you configure how tokens are validated.

The most important property is TokenValidationParameters.

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            // configured below
        };
    });

Validating the Issuer and Audience

Set ValidateIssuer and ValidateAudience to ensure the token came from your trusted authority and was meant for your API.

ValidIssuer and ValidAudience must match the iss and aud claims in the token.

var tvp = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidIssuer = builder.Configuration["Jwt:Issuer"],
    ValidateAudience = true,
    ValidAudience = builder.Configuration["Jwt:Audience"]
};

Validating the Signing Key

The most security-critical check: ValidateIssuerSigningKey with an IssuerSigningKey. This confirms the signature was produced with your secret.

For symmetric (HS256) signing you build a SymmetricSecurityKey from the secret bytes.

var key = new SymmetricSecurityKey(
    Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!));

tvp.ValidateIssuerSigningKey = true;
tvp.IssuerSigningKey = key;

Validating Lifetime

ValidateLifetime = true rejects expired tokens by checking the exp and nbf claims.

ClockSkew adds tolerance for clock differences between servers. The default is 5 minutes; tighten it for short-lived tokens.

tvp.ValidateLifetime = true;
tvp.ClockSkew = TimeSpan.FromSeconds(30);

Putting It Together

A complete, production-style configuration combines all the validation parameters in one place.

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Jwt:Audience"],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(30)
        };
    });

The Middleware Order

Configuration alone is not enough. You must add the authentication and authorization middleware to the pipeline, and the order matters.

UseAuthentication must come before UseAuthorization.

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

Protecting Endpoints

Once configured, mark endpoints with [Authorize] (controllers) or .RequireAuthorization() (minimal APIs) to require a valid token.

app.MapGet("/me", (ClaimsPrincipal user) =>
        new { id = user.FindFirstValue(ClaimTypes.NameIdentifier) })
   .RequireAuthorization();

Using a Trusted Authority

If your tokens come from an external identity provider (e.g. Microsoft Entra ID, Auth0), set the Authority instead of a static key.

The handler then downloads the signing keys from the provider's discovery document automatically.

.AddJwtBearer(options =>
{
    options.Authority = "https://login.myidp.com/";
    options.Audience = "my-api";
    // Keys are fetched from the OpenID configuration endpoint
});

Reading Validation Failures

JWT Bearer raises events you can hook for logging or custom responses, such as OnAuthenticationFailed and OnChallenge.

options.Events = new JwtBearerEvents
{
    OnAuthenticationFailed = ctx =>
    {
        logger.LogWarning(ctx.Exception, "JWT validation failed");
        return Task.CompletedTask;
    }
};

Quick Check

Check your grasp of pipeline configuration.

Recap

You configured JWT Bearer authentication:

  • AddAuthentication(...).AddJwtBearer(...) registers the handler.
  • TokenValidationParameters controls issuer, audience, signing key and lifetime checks.
  • UseAuthentication() must precede UseAuthorization().
  • Use Authority for external identity providers.

Next: how to issue your own tokens.

Frequently asked questions

Is the “Configuring JWT Bearer Authentication” lesson free?

Yes — the full text of “Configuring JWT Bearer Authentication” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Configuring JWT Bearer Authentication”?

Wire up token validation in the pipeline. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Configuring JWT Bearer Authentication” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. JWT Structure and Claims
  2. Configuring JWT Bearer Authentication
  3. Issuing Tokens
  4. Refresh Tokens and Expiry
← Back to C# Academy