# Authentication and Authorization with JWT — .NET Core: Build, Test and Ship Web APIs

Source: https://www.geekswithgeeks.com/en/dotnet-core/sec-jwt-auth

> Protect endpoints with JWT bearer tokens and understand authentication versus authorization.

## Who are you, what may you do

**Authentication** answers "who is this?" and **authorization** answers "may they do this?". A JWT is a signed token the client sends in the `Authorization: Bearer ...` header; the API checks its signature, issuer, audience and expiry.

## Wire up JWT bearer

Add the `Microsoft.AspNetCore.Authentication.JwtBearer` package. Authority and audience normally come from your identity provider such as Entra ID, Auth0 or Keycloak.

```csharp
builder.Services.AddAuthentication("Bearer").AddJwtBearer(o =>
{
    o.Authority = builder.Configuration["Auth:Authority"];
    o.Audience  = builder.Configuration["Auth:Audience"];
});
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/me", (ClaimsPrincipal user) => user.Identity?.Name)
   .RequireAuthorization();
```

## Keep tokens short-lived

Never put secrets in a JWT: it is only signed, not encrypted, so anyone can read the payload. Use short expiry, HTTPS only, and a refresh flow. Prefer an identity provider over writing your own login system.

**Quiz:** Which call makes an endpoint require a signed-in user?

- [ ] .AllowAnonymous()
- [ ] .WithName()
- [x] .RequireAuthorization()
- [ ] .Produces()

*Answer:* .RequireAuthorization(). `RequireAuthorization()` makes the endpoint reject requests that are not authenticated and authorized.
