Your API works. Now it needs to know who is calling it, and to turn away everyone else.
For APIs consumed by mobile apps, single-page apps or other services, the usual answer is a JSON Web Token (JWT) sent in the Authorization header. ASP.NET Core supports this out of the box. The setup isn’t long, but there are a few places where small mistakes produce a confusing 401 that tells you nothing.
This guide builds a minimal working setup on .NET 10, then covers the parts that tutorials tend to skip.
How JWT auth works, in one paragraph
The client sends a username and password to a login endpoint. If they’re valid, the server returns a signed token containing a few facts (“claims”) about the user, such as their ID and role, plus an expiry time. The client sends that token with every later request as Authorization: Bearer <token>. The server checks the signature and expiry. If both are fine, it trusts the claims without a database lookup. That’s what makes JWTs fast, and also why you must keep them short-lived.
One thing to be clear on: a JWT is signed, not encrypted. Anyone holding the token can decode it and read the claims. Never put passwords, Aadhaar numbers or other sensitive data inside one.
Step 1: Add the package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
That package brings in Microsoft.IdentityModel.JsonWebTokens, which contains JsonWebTokenHandler. It’s the newer, faster handler that ASP.NET Core itself has used for validation since .NET 8. We’ll use it to create tokens too.
Step 2: Configure the issuer, audience and key
In appsettings.json, keep the non-secret values:
{
"Jwt": {
"Issuer": "https://api.yourcompany.com",
"Audience": "yourcompany-clients"
}
}
The signing key is a secret, so it does not go in appsettings.json. During development, use User Secrets:
dotnet user-secrets init
dotnet user-secrets set "Jwt:Key" "<a long random value>"
Generate a proper random value rather than typing a sentence. In PowerShell 7:
[Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(48))
Or with OpenSSL: openssl rand -base64 48.
For HS256, the key must be at least 256 bits (32 bytes). A shorter key makes token creation throw an exception. In production, supply Jwt__Key as an environment variable, through IIS application settings, or from a vault such as Azure Key Vault.
Step 3: The complete Program.cs
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
var jwt = builder.Configuration.GetSection("Jwt");
var signingKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwt["Key"]
?? throw new InvalidOperationException("Jwt:Key is not configured")));
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false; // keep "sub" and "role" as-is
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwt["Issuer"],
ValidateAudience = true,
ValidAudience = jwt["Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
NameClaimType = "sub",
RoleClaimType = "role"
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
// 1. Login: exchange credentials for a token
app.MapPost("/auth/login", (LoginRequest req) =>
{
// Replace with a real user lookup and password-hash check.
if (req.Username != "demo" || req.Password != "demo-password")
return Results.Unauthorized();
var handler = new JsonWebTokenHandler();
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = jwt["Issuer"],
Audience = jwt["Audience"],
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, req.Username),
new Claim("role", "Admin"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}),
Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = new SigningCredentials(
signingKey, SecurityAlgorithms.HmacSha256)
});
return Results.Ok(new { access_token = token, token_type = "Bearer", expires_in = 900 });
});
// 2. Any signed-in user
app.MapGet("/me", (ClaimsPrincipal user) =>
Results.Ok(new { user = user.Identity?.Name }))
.RequireAuthorization();
// 3. Admins only
app.MapGet("/admin/reports", () => Results.Ok("Top secret numbers"))
.RequireAuthorization(policy => policy.RequireRole("Admin"));
app.Run();
record LoginRequest(string Username, string Password);
If you use controllers instead of minimal APIs, the setup is identical. Just decorate controllers or actions with [Authorize] or [Authorize(Roles = "Admin")].
Step 4: Try it
# Get a token
curl -s -X POST https://localhost:5001/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"demo","password":"demo-password"}'
# Use it
curl https://localhost:5001/me -H "Authorization: Bearer <paste token here>"
Paste the token into a JWT decoder to see the claims inside. Do this only with test tokens, never with production ones.
The four mistakes behind most mysterious 401s
1. Middleware in the wrong order. UseAuthentication() must come before UseAuthorization(), and both must come after routing and before the endpoints run. With minimal APIs the template handles routing for you; just keep those two lines in that order.
2. Claim name mapping. By default, ASP.NET Core renames incoming JWT claims to long XML-style URIs. For example, sub becomes http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier. Then User.FindFirst("sub") returns null and role checks quietly fail. Setting MapInboundClaims = false and telling the validator which claims hold the name and role (NameClaimType, RoleClaimType) makes everything predictable.
3. Issuer or audience mismatch. The values used to create the token must exactly match the values used to validate it, including trailing slashes and http vs https. Read both from the same configuration section, as above.
4. Clock skew. The default tolerance is five minutes. That means a “15-minute” token actually works for about 20. We set ClockSkew to 30 seconds. Don’t set it to zero, because servers’ clocks drift slightly and you’ll get random early rejections.
Debugging tip: when a request returns 401, look at the WWW-Authenticate response header. It often says exactly why, for example error="invalid_token", error_description="The signature key was not found". You can also log options.Events.OnAuthenticationFailed during development.
Access tokens should be short; that’s what refresh tokens are for
Once a JWT is issued, you can’t easily revoke it. It’s valid until it expires. That’s why access tokens should live minutes, not days.
To avoid making users log in every 15 minutes, issue a refresh token alongside the access token:
- It’s a long random string, not a JWT, stored in your database with an expiry and the user ID.
- When the access token expires, the client sends the refresh token to
/auth/refreshand gets a new pair. - Rotate it: each refresh token can be used once. If an old one is reused, assume it was stolen and revoke that user’s whole token family.
- Logging out or disabling a user deletes their refresh tokens, which cuts off access within one access-token lifetime.
For browser apps, keep the refresh token in an HttpOnly, Secure, SameSite cookie rather than localStorage, where any injected script could read it.
HS256 or RS256?
We used HS256, a shared secret. It’s simple and perfect when the same API both issues and validates tokens.
If several services need to validate tokens but only one should issue them, switch to RS256 or ES256. The issuer signs with a private key, and everyone else validates with the public key, so a compromised downstream service can’t mint tokens.
At that point, consider whether you should be issuing tokens at all. An identity provider such as Microsoft Entra ID, Auth0, Keycloak or Duende IdentityServer gives you login screens, MFA, password resets and key rotation. Your API then only validates tokens, and the AddJwtBearer setup shrinks to setting the Authority and Audience.
Before you go live
- ☐ Signing key comes from a secret store, is at least 32 random bytes, and differs between environments
- ☐ Access tokens expire in 5–30 minutes
- ☐ HTTPS only, because a bearer token sent over plain HTTP can be stolen and replayed
- ☐ Passwords are hashed (ASP.NET Core Identity’s
PasswordHasheror similar), never stored in plain text - ☐ The login endpoint is rate-limited (
builder.Services.AddRateLimiter) to slow down password guessing - ☐ No sensitive personal data inside the token
- ☐ Refresh tokens are stored server-side, rotated and revocable
Get these right and JWT authentication is one of the least eventful parts of your API, which is exactly what authentication should be.
Leave a Comment