What Is a JWT? How JSON Web Tokens Work (With ASP.NET Core Examples)

Quick answer: A JWT (JSON Web Token) is a compact, URL-safe string that carries JSON data, called claims, between two parties. It has three Base64URL parts separated by dots: a header that names the signing algorithm, a payload with claims such as the user ID and expiry time, and a signature that proves the token was issued by someone holding the key and has not been changed. JWTs are signed, not encrypted, so anyone can read the payload; servers trust a token only after validating its signature, issuer, audience and expiry.
JWTs are used for API authentication, single sign-on and OpenID Connect. This guide explains how they work, the claims you will see most, the security mistakes to avoid and how to validate tokens in ASP.NET Core. You can decode any token while you read with our free JWT decoder. This article is part of our Programming and Development guide.
What Is a JWT?
JSON Web Token is an open standard defined in RFC 7519. A JWT is a string like this, shortened here:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NSIsIm5hbWUiOiJLYW1yYW4ifQ.JrC0dm4zu1aF3AXBXqS9...Because it is self-contained, an API can check a JWT without looking up a session in a database: the claims travel inside the token, and the signature proves they are genuine. That is why JWTs are popular for stateless APIs, microservices and mobile apps.
The Three Parts of a JWT
| Part | Contains | Example (decoded) |
|---|---|---|
| Header | The token type and signing algorithm | {"alg":"HS256","typ":"JWT"} |
| Payload | Claims about the user and the token | {"sub":"12345","name":"Kamran","exp":1764003600} |
| Signature | A cryptographic signature of the header and payload | Binary data, Base64URL encoded |
Each part is Base64URL encoded, which is Base64 with - and _ instead of + and / and without padding, so the token can be used safely in URLs and HTTP headers. The signature is calculated over the exact text header.payload, so changing a single character in either part makes the signature invalid.
Common JWT Claims
The standard defines seven registered claims. All time claims use a NumericDate: the number of seconds since 1 January 1970 UTC.
| Claim | Name | Meaning |
|---|---|---|
iss | Issuer | Who created and signed the token |
sub | Subject | The user or entity the token is about |
aud | Audience | The API or app the token is meant for |
exp | Expiration time | The token must be rejected after this time |
nbf | Not before | The token must be rejected before this time |
iat | Issued at | When the token was created |
jti | JWT ID | A unique identifier, useful to detect replayed tokens |
Apps add their own claims too, such as name, email, role or scope. Paste a token into the JWT decoder to see each claim explained and every timestamp converted to a readable date.
How JWT Authentication Works
- The user signs in with a password, a social login or single sign-on.
- The authentication server creates a JWT with claims such as
sub,audandexp, and signs it. - The client stores the token and sends it with each request in the header
Authorization: Bearer <token>. - The API validates the signature and claims. If everything is valid, it trusts the claims and processes the request.
- When the short-lived access token expires, the client uses a refresh token to get a new one.
Signing Algorithms: HS256 vs RS256 vs ES256
| Algorithm | Key type | Best for |
|---|---|---|
| HS256 | One shared secret (HMAC with SHA-256) | A single app that both issues and validates tokens |
| RS256 | RSA private key signs, public key verifies | Many APIs validating tokens from one identity provider |
| ES256 | Elliptic-curve (P-256) key pair | The same as RS256, with smaller keys and signatures |
With HS256 every service that validates tokens must hold the secret, which also allows it to create tokens. With RS256 or ES256, only the identity provider holds the private key; APIs only need the public key.
Is a JWT Encrypted?
A normal JWT is signed, not encrypted. The payload is only Base64URL encoded, so anyone who has the token can read it. Never put passwords, card numbers or other secrets in a JWT payload. If the contents must be hidden, use an encrypted JWT (JWE), which has five parts instead of three, or keep the sensitive data on the server.
JWT Security Mistakes to Avoid
- Accepting
alg: none. An unsigned token must always be rejected. Configure your library with the exact algorithms you expect. - Algorithm confusion. If an API that expects RS256 also accepts HS256, an attacker may sign a token using the public key as an HMAC secret. Pin the algorithm.
- Weak HMAC secrets. Short or guessable secrets can be brute-forced offline. Use a long random key, at least 256 bits for HS256.
- Long-lived access tokens. A stolen token works until it expires. Keep access tokens short-lived and use refresh tokens.
- Skipping audience and issuer checks. A valid token for one app should not be accepted by another.
- Storing tokens where scripts can read them. Tokens in
localStoragecan be stolen through an XSS bug; many apps prefer HttpOnly, Secure cookies for browser sessions.
Validating a JWT in ASP.NET Core
ASP.NET Core validates bearer tokens with the JWT Bearer authentication handler. A typical setup in Program.cs looks like this:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://auth.example.com",
ValidateAudience = true,
ValidAudience = "my-api",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/me", (System.Security.Claims.ClaimsPrincipal user) =>
user.FindFirst("sub")?.Value ?? "unknown")
.RequireAuthorization();
app.Run();If you use an identity provider such as Microsoft Entra ID or Auth0, set options.Authority instead of a signing key; the handler then downloads the provider’s public keys automatically. Microsoft’s JWT bearer authentication guide covers these options in detail.
Two details that often confuse developers:
- Clock skew. By default the validator allows a small clock difference (five minutes) when checking
expandnbf, so a token may still work slightly after it expires. LowerClockSkewif you need strict expiry. - .NET 8 token type. From .NET 8 the handler uses
JsonWebTokenHandlerby default, and the token passed to events is aJsonWebTokenrather than aJwtSecurityToken, as documented in the .NET 8 breaking changes. Update any code that casts the token type.
New to the framework? Start with our ASP.NET Core tutorial for beginners.
How to Debug JWT Problems
| Error or symptom | What to check |
|---|---|
| 401 with “invalid_token” | Decode the token and compare iss and aud with your API settings |
| “The token is expired” | Compare exp with the current UTC time; check server clocks |
| “Signature validation failed” | Wrong key, key from another environment, or a missing key ID (kid) match |
| Token is not a JWT | Some providers issue opaque access tokens that only the provider can read |
| Payload claims missing | Check the scopes requested and the claim mapping in your identity provider |
The quickest first step is to paste the token into our JWT decoder: it shows the issuer, audience and expiry immediately and can confirm whether your key verifies the signature. If the payload JSON looks broken, see common JSON errors and how to fix them.
Frequently Asked Questions
What does JWT stand for?
JWT stands for JSON Web Token. It is usually pronounced “jot”.
Is a JWT the same as OAuth?
No. OAuth 2.0 is an authorization framework; JWT is a token format. Many OAuth and OpenID Connect providers issue access tokens and ID tokens as JWTs, but OAuth does not require them.
Can a JWT be revoked?
Not directly, because servers validate it without a database lookup. Common approaches are short expiry times, refresh token rotation and a deny list of token IDs (jti) for urgent cases.
Where should I store a JWT in a web app?
For browser apps, an HttpOnly, Secure, SameSite cookie protects the token from JavaScript. If you store it in memory or localStorage, strong XSS protection becomes critical.
How long should a JWT be valid?
Access tokens are commonly valid for minutes to an hour. Longer sessions should use refresh tokens that can be revoked.
Final Thoughts
A JWT is just signed JSON: easy to read, easy to pass between services and safe only when it is validated properly. Check the signature with the right key, pin the algorithm, verify issuer, audience and expiry, and keep secrets out of the payload. Try it now with our free, private JWT decoder, and explore more in the Programming and Development guide.