ASP.NET Core Web API Interview Question #57

How do you configure JWT bearer authentication in ASP.NET Core?

Authentication, Authorization, JWT & API Security Mid-Level Intermediate

Quick Interview Answer

Register the JWT bearer authentication handler and configure token-validation parameters that match the trusted token issuer. The request pipeline must also execute authentication and authorization middleware before protected endpoints.

Detailed Explanation

Register the JWT bearer authentication handler and configure token-validation parameters that match the trusted token issuer. The request pipeline must also execute authentication and authorization middleware before protected endpoints.

Production configuration should obtain issuer, audience, and signing-key information from secure configuration or an identity provider rather than hard-coding secrets in source code.

Code Example

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters =
            new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true
            };
    });

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