JWT Bearer Authentication in ASP.NET Core
On this page
Learning Objective
Read and validate a JWT correctly, configure ASP.NET Core to check issuer, audience, lifetime, signature and algorithm, explain the classic algorithm confusion and none attacks, and decide what belongs inside a token and how long it should live.
Concept Explanation
A JSON Web Token is three base64url-encoded parts separated by dots: a header describing the algorithm and key, a payload of claims, and a signature computed over the first two parts. The claims might state who the subject is, who issued the token, which audience it is intended for, when it expires, and what scopes or roles apply. The signature proves the token was issued by whoever holds the signing key and that nobody has modified it. Crucially, the payload is only encoded, not encrypted. Anyone holding the token can read it, so it must never contain secrets, and the only guarantee is integrity, not confidentiality.
Bearer authentication means whoever presents the token is treated as the user, exactly like a key, so the API must validate every property that makes a token trustworthy. The signature must verify against a key you trust, and the algorithm must be one you expect. The issuer must be your identity provider, because a validly signed token from some other provider must not be accepted. The audience must be your API, so a token issued for a different application cannot be replayed against you. The lifetime must be checked, with only a small clock skew tolerance. Missing any of these checks is a vulnerability, not a shortcut, and each corresponds to a real attack.
The two best-known attacks target the algorithm field, which comes from the untrusted token itself. In the none attack, some libraries accepted tokens declaring alg none and skipped signature verification entirely. In the algorithm confusion attack, a server expecting an asymmetric RS256 signature could be tricked into treating its own public key as an HMAC secret when the header said HS256, letting an attacker who knows the public key forge valid tokens. Both were disclosed in 2015 by Tim McLean and stem from letting the token choose how it is verified. The defense is for the server to fix the allowed algorithms and keys in configuration, never trusting the header, and modern libraries reject none by default.
For the lifetime and content of tokens, keep access tokens short, five to fifteen minutes, so a stolen token is only briefly useful, and use refresh tokens, held more carefully, to obtain new ones. Put only what the API needs into claims: a stable subject identifier, scopes or roles, and perhaps a tenant. Avoid personal data and anything that changes often, because a token is a snapshot that can be stale for its entire lifetime. Validate signatures with keys fetched from the provider's JWKS endpoint, which supports key rotation, instead of copying a static key into configuration. In .NET the JsonWebTokenHandler, the default since .NET 8, performs this validation faster than the older handler.
| Validation | What it defends against | Setting |
|---|---|---|
| Signature | Forged or modified tokens | Keys from the provider's JWKS endpoint |
| Algorithm allowlist | none and RS/HS confusion attacks | ValidAlgorithms with only expected values |
| Issuer | Tokens from another provider | ValidIssuer or Authority |
| Audience | Tokens issued for a different API | ValidAudience |
| Lifetime | Use of expired tokens | ValidateLifetime, small ClockSkew |
| Token type or scope | Using an ID token as an access token | Check typ and required scopes in policy |
Worked Example: Strict Bearer Validation, a Scope Policy and Rejection Tests
The configuration validates against an identity provider using its metadata, pins the algorithm and audience, and enforces a scope through a policy. The tests craft hostile tokens to prove they are rejected.
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Auth:Authority"]; // discovery document and JWKS are fetched from here
o.MapInboundClaims = false; // keep claim names as issued, e.g. "sub", "scp"
o.RequireHttpsMetadata = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Auth:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["Auth:Audience"], // this API, and nobody else
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
RequireExpirationTime = true,
ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 } // never trust the alg in the token header
};
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("notes.write", p => p.RequireAuthenticatedUser().RequireClaim("scp", "notes.write"));
app.MapPost("/api/notes", CreateNote).RequireAuthorization("notes.write");// Hostile tokens must fail. Build them in tests with a throwaway key.
public class JwtRejectionTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
[Fact] public async Task Alg_none_token_is_rejected() =>
Assert.Equal(HttpStatusCode.Unauthorized, await Call(TokenBuilder.UnsignedWithAlgNone(sub: "admin")));
[Fact] public async Task Token_signed_with_an_unknown_key_is_rejected() =>
Assert.Equal(HttpStatusCode.Unauthorized, await Call(TokenBuilder.SignedWithRandomKey()));
[Fact] public async Task Token_for_another_audience_is_rejected() =>
Assert.Equal(HttpStatusCode.Unauthorized, await Call(factory.ValidToken(audience: "some-other-api")));
[Fact] public async Task Expired_token_is_rejected() =>
Assert.Equal(HttpStatusCode.Unauthorized, await Call(factory.ValidToken(expires: DateTime.UtcNow.AddMinutes(-5))));
[Fact] public async Task Missing_scope_is_forbidden_not_unauthorized() =>
Assert.Equal(HttpStatusCode.Forbidden, await Call(factory.ValidToken(scopes: "notes.read")));
private async Task<HttpStatusCode> Call(string jwt)
{
var client = factory.CreateClient();
client.DefaultRequestHeaders.Authorization = new("Bearer", jwt);
return (await client.PostAsJsonAsync("/api/notes", new { title = "x" })).StatusCode;
}
}Reading a token during debugging is easy: paste it into a decoder, or split on the dots and base64url-decode the middle segment. That readability is exactly why nothing sensitive belongs inside, and why you should never paste production tokens into a website you do not control, as they are live credentials.
Real-World Examples
- In March 2015, security researcher Tim McLean published Critical vulnerabilities in JSON Web Token libraries, showing that several popular libraries accepted tokens with alg none and were vulnerable to RS256 to HS256 confusion. Library maintainers patched, and the disclosure led to the guidance that the verifier must choose the algorithm, not the token.
- The IETF published RFC 8725, JSON Web Token Best Current Practices, in 2020, codifying recommendations such as always validating issuer and audience, rejecting none, using explicit algorithm allowlists, and using typed tokens to prevent one kind of token being accepted as another. It is a short, practical checklist that directly matches the validation parameters configured above.
Review Questions & Answers
A token can be validly signed by your identity provider yet intended for a different application. Without an audience check, a token obtained for some other service, perhaps with weaker protections, could be replayed against your API and accepted. Checking that the audience is your API ensures a token is only valid where it was meant to be used.
If a server verifies tokens using whatever algorithm the token header names, an attacker can change RS256 to HS256 and sign the token with the server's public key as if it were an HMAC secret, which the server then accepts. The prevention is to configure the allowed algorithms and key types on the server so the token's header cannot influence how verification is done.
A bearer token is usable by anyone who obtains it until it expires, so a short lifetime limits the damage of theft. Claims are a snapshot fixed at issue time, so roles or permissions that change stay stale for the whole lifetime, and personal data in an unencrypted payload is readable by anyone who sees the token. Keep only identifiers and scopes.
A 401 means authentication failed: the token was missing, forged, expired, or otherwise invalid, so the caller is not identified. A 403 means the token is valid and the caller is known, but lacks a required scope or permission for that action. Distinguishing them helps clients decide whether to reauthenticate or show an access denied message.