JWT authentication is a standard method for securely transmitting identity and authorization data between systems using a compact, self-contained JSON token. It enables stateless authentication in APIs and web services by verifying the token's signature and validating its claims.
JWTs are issued by trusted authorities and validated by receiving services. They contain claims such as user ID, expiration time, and permissions. A valid JWT proves the sender's identity and ensures the data hasn't been altered.
When a user logs in, the server issues a JWT containing encoded user details and a digital signature. Subsequent requests include this token in the Authorization header. The receiving service verifies the signature and extracts the claims to determine access rights.
Authentication begins when a client sends credentials to an authentication endpoint. If valid, the server generates a JWT with a payload, signs it with a secret key or private key, and returns it to the client.
The payload typically includes:
The token is structured as three base64-encoded parts separated by dots: header.payload.signature. The server decodes the header and payload, then validates the signature using the known secret or public key.
If the signature is invalid or the token has expired, the request is rejected. Valid tokens grant access based on the claims they carry.
JWTs fall into two categories based on signing method:
| Type | Signing Method | Use Case | Security Risk |
|---|---|---|---|
| HS256 | Secret key (symmetric) | Internal microservices, single-team apps | Key exposure compromises all tokens |
| RS256 | Private key (asymmetric) | Public APIs, multi-party systems | Only the private key holder can issue tokens |
HS256 uses a shared secret. Both issuer and verifier must store and protect the same key. This works well in closed environments but fails if the key leaks.
RS256 uses a private-public key pair. The issuer signs with a private key. Verifiers use the public key to validate. This allows third parties to verify authenticity without seeing the private key.
For example, Okta uses RS256 to issue tokens for enterprise applications. The public key is published via a well-known URL, allowing any service to verify tokens without sharing secrets.
Many developers assume JWTs are inherently secure because they're signed. That's incorrect. A signed token prevents tampering but doesn't prevent reuse or unauthorized access.
JWTs are not encrypted by default. The payload is base64-encoded, not encrypted. Anyone who intercepts the token can read the claims unless encryption is explicitly added.
A critical mistake is failing to validate the token's expiration. A token with a long lifespan increases risk. The exp claim must be checked on every request. According to OWASP, unchecked expiration is a top API security flaw.
Another error is storing JWTs in localStorage. If a site has XSS vulnerabilities, attackers can steal the token and impersonate the user. Instead, store tokens in HTTP-only cookies.
I once debugged a login system where tokens were reused across sessions. The app didn't invalidate old tokens after logout. A user logged out, but their old JWT still granted access. This was fixed by adding a token blacklist and checking against it on each request.
JWT authentication differs from session-based authentication in key ways:
| Feature | JWT Authentication | Session-Based Auth |
|---|---|---|
| State Management | Stateless (server doesn't store session data) | Stateful (server stores session in memory or DB) |
| Scalability | High (any server can validate tokens) | Limited (session affinity required) |
| Token Revocation | Requires external mechanism (e.g., blacklist) | Simple (delete session from storage) |
| Performance | Fast (no DB lookup) | Slower (DB or cache lookup needed) |
JWTs are ideal for distributed systems, mobile apps, and APIs. Session-based auth suits traditional web apps where server-side control is preferred.
JWTs are often confused with OAuth 2.0. JWTs are a format. OAuth 2.0 is a protocol. You can use JWTs within OAuth 2.0 flows-such as in OpenID Connect-to represent identity tokens.
For example, when logging into a third-party app via Google, the app receives an ID token in JWT format. This token contains user info and is verified using Google's public keys.
Follow these guidelines to implement JWT authentication securely:
iss and aud claims.Consider this example: A weather API requires authenticated access. A user logs in with email and password. The server responds with:
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIsImV4cCI6MTUxNjI0MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The client includes this token in all subsequent requests. The API validates the signature using the public key from https://auth.example.com/.well-known/jwks.json. It checks that the token hasn't expired and that the audience matches the API's identifier.
If the token is valid, the API returns weather data. If not, it returns a 401 Unauthorized response.
JWT authentication is not a silver bullet. It requires careful implementation. But when done correctly, it provides a secure, scalable way to manage access across modern applications.