This article explains what a JSON Web Token (JWT) is, how it works, and why it is used for authentication and information exchange. You will learn the structure of a JWT, how it is created and verified, common use cases, and security pitfalls to avoid.
Background: Why JWTs Exist
Before JWTs, web sessions were usually managed with server-side session IDs. When a user logged in, the server stored a session record in memory or a database and sent the client a cookie containing the session ID. On every request, the server looked up that ID to identify the user. This works fine for a single server, but it becomes a problem in distributed systems with many servers, because every server needs access to the same session store. It also makes scaling harder and can create a single point of failure.
JWTs were introduced as a way to move session data to the client side. Instead of storing session information on the server, the server signs a token that contains the user’s identity and any other claims (like roles or permissions). The client sends that token with each request, and the server verifies the signature to trust the data. Because the token is self-contained, the server does not need to keep any session state. This statelessness is the key advantage of JWTs.
What Exactly Is a JWT?
JWT stands for JSON Web Token. It is an open standard (RFC 7519) that defines a compact, URL-safe way to represent claims between two parties. A JWT is a string of three parts separated by dots:
- Header – contains the signing algorithm and token type.
- Payload – contains the claims (data about the user and metadata).
- Signature – used to verify that the token has not been tampered with.
Each part is Base64Url-encoded JSON. The three parts are concatenated with dots, like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The header and payload are not encrypted; they are only Base64Url-encoded, so anyone can read them. The signature is what ensures the token has not been altered. If you need to hide the data, you must use JWE (JSON Web Encryption), which is a separate standard.
How JWT Authentication Works
Here is the typical flow when a user logs in with a JWT:
- The user sends credentials (username/password) to the server.
- The server verifies the credentials and creates a JWT with the user’s ID and any other claims (like role).
- The server signs the token with a secret key (HMAC) or a private key (RSA/ECDSA).
- The server sends the token back to the client.
- The client stores the token (usually in localStorage or a cookie) and sends it in the
Authorizationheader asBearer <token>for each subsequent request. - The server verifies the signature and optionally checks the expiration time, then trusts the claims in the token.
Because the server only needs the secret or public key to verify the signature, it does not need to store any session data. This makes JWTs ideal for microservices and APIs where you want to avoid a central session store.
JWT Structure in Detail
Header
The header typically looks like this:
{"alg": "HS256", "typ": "JWT"}
alg– the signing algorithm (e.g., HS256 for HMAC-SHA256, RS256 for RSA-SHA256).typ– the token type, usually "JWT".
Payload
The payload contains claims. There are three types of claims:
- Registered claims – predefined, like
sub(subject),iat(issued at),exp(expiration),aud(audience). - Public claims – custom claims defined by the application, but should be registered in the IANA JWT registry to avoid collisions.
- Private claims – custom claims agreed upon by the parties that use the token.
Example payload:
{"sub": "1234567890", "name": "John Doe", "admin": true, "iat": 1516239022}
Signature
The signature is created by taking the encoded header and payload, and signing them with the algorithm specified in the header. For HMAC-SHA256, the formula is:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
For RSA or ECDSA, the same input is signed with a private key, and the public key is used for verification.
How to Choose a Signing Algorithm
The two most common algorithms are HS256 and RS256.
- HS256 (HMAC with SHA-256) – uses a single secret key for both signing and verification. It is simple and fast, but the secret must be shared between all servers that verify tokens. If the secret leaks, anyone can forge tokens.
- RS256 (RSA with SHA-256) – uses a private key to sign and a public key to verify. This is better for microservices because the public key can be distributed freely, and the private key stays with the authentication server. It is slower than HMAC but more secure in distributed environments.
For most new applications, RS256 is recommended because it allows the verification server to not hold the signing key. However, if you have a simple monolithic app, HS256 is often sufficient.
Common Problems and Security Pitfalls
JWTs are secure only if implemented correctly. Here are the most common mistakes:
- Using a weak secret – if the HMAC secret is short or guessable, attackers can brute-force it and forge tokens.
- Not validating the algorithm – an attacker can change the header to "none" or switch from RS256 to HS256 and sign with the public key. Always verify the algorithm matches the expected one.
- Not checking expiration – if you do not validate the
expclaim, a stolen token works forever. Always check expiration and reject expired tokens. - Storing tokens in localStorage – this makes them vulnerable to XSS attacks. Using HTTP-only cookies is safer, but then you need CSRF protection.
- Putting sensitive data in the payload – remember, the payload is only Base64-encoded, not encrypted. Never put passwords or other secrets in a JWT.
Another misconception is that JWTs are "stateless" and therefore cannot be revoked. While that is true by design, you can implement a denylist or use short expiration times to mitigate the risk.
JWT vs. Session Cookies
Both JWTs and traditional session cookies are used for authentication, but they have different trade-offs.
| Feature | JWT | Session Cookie |
|---|---|---|
| Storage | Client-side (token) | Server-side (session record) |
| Scalability | No session store needed | Requires shared session store |
| Revocation | Harder (need denylist) | Easy (delete session) |
| Cross-domain | Works well (Authorization header) | Problematic with CORS |
| Security | Depends on implementation | CSRF protection needed |
For APIs and microservices, JWTs are often preferred because they are stateless and work well with mobile clients. For traditional server-rendered web apps, session cookies are simpler and offer easier revocation.
Frequently Asked Questions
What does JWT stand for?
JWT stands for JSON Web Token. It is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object.
Is a JWT encrypted?
No. The header and payload are only Base64Url-encoded, which is not encryption. Anyone can decode them and read the contents. The signature only ensures the token has not been tampered with. If you need confidentiality, use JWE (JSON Web Encryption).
How long can a JWT be valid?
It depends on the application. Common expiration times are 15 minutes to a few hours for access tokens, and longer (days or weeks) for refresh tokens. The expiration is set in the exp claim, and the server should reject tokens past that time.
Can a JWT be revoked before it expires?
Not by default. Because JWTs are stateless, the server cannot invalidate them simply by deleting a session. To revoke a token, you need a denylist (store the token’s ID or jti until expiration) or use short expiration times with a refresh token mechanism.
What is the difference between JWT and OAuth?
JWT is a token format, while OAuth is an authorization framework. OAuth 2.0 does not require JWTs; it can use opaque tokens. However, JWTs are often used as OAuth access tokens because they are self-contained and can carry claims.
Is it safe to store a JWT in localStorage?
Storing a JWT in localStorage is risky because any XSS vulnerability can steal it. Using HTTP-only cookies is safer for web apps, but that requires CSRF protection. For mobile apps or APIs, storing the token in memory or a secure storage is recommended.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It