2 · Data and boundaries · 30 MIN
Authentication and authorization are different checks
A verified identity must still be authorized for the requested operation.
The JWT bearer handler validates tokens against a configured HTTPS identity authority and expected audience. RequireAuthorization ensures anonymous requests do not enter the endpoint. A real private-resource handler must additionally match the record’s owner to a stable subject from validated claims. Do not trust an owner field supplied in the request. This exercise requires an actual identity provider and compatible bearer package; the placeholder authority is deliberately not a functioning login system.
Keep HTTPS metadata validation enabled.
Read the example
// Add Microsoft.AspNetCore.Authentication.JwtBearer matching your .NET major version.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder=WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options=>{
options.Authority="https://YOUR-IDENTITY-PROVIDER";
options.Audience="learning-api";
options.RequireHttpsMetadata=true;
});
builder.Services.AddAuthorization();
var app=builder.Build();
app.UseAuthentication();app.UseAuthorization();
app.MapGet("/private",()=>new {message="Authenticated access"}).RequireAuthorization();
app.Run();Check the expected output
Without a valid bearer token, /private returns 401. With a correctly configured provider and valid audience token, it returns the private message.
Your challenge
Configure a development identity provider, add an owner-checked plan endpoint and test missing, expired and wrong-audience tokens.
Solution cost: Token validation plus the selected authorization policy. time · Bounded token and claims data; provider metadata cache is separate. space
Common trap
Decoding a JWT without validating its signature, issuer and audience is not authentication.
Study the project implementation
// Add Microsoft.AspNetCore.Authentication.JwtBearer matching your .NET major version.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder=WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options=>{
options.Authority="https://YOUR-IDENTITY-PROVIDER";
options.Audience="learning-api";
options.RequireHttpsMetadata=true;
});
builder.Services.AddAuthorization();
var app=builder.Build();
app.UseAuthentication();app.UseAuthorization();
app.MapGet("/private",()=>new {message="Authenticated access"}).RequireAuthorization();
app.Run();Further reading: Official documentation
Next lesson: Cancellation and safe error responses →