Understanding JSON Web Tokens (JWT): A Complete Guide

A comprehensive guide to JWTs: what they are, how they work, and their role in modern authentication.

basicsauthenticationsecurity

What is a JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and information exchange.

JWT Structure

A JWT consists of three parts separated by dots:

xxxxx.yyyyy.zzzzz
Header.Payload.Signature

1. Header

Contains the token type and signing algorithm:

{
"alg": "HS256",
"typ": "JWT"
}

2. Payload

Contains the claims (statements about the user and metadata):

{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022,
"exp": 1516242622
}

3. Signature

Verifies the token hasn't been tampered with:

HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)

Standard Claims

ClaimNameDescription
issIssuerWho created the token
subSubjectWho the token is about
audAudienceWho the token is for
expExpirationWhen the token expires
iatIssued AtWhen the token was created
nbfNot BeforeToken not valid before this time

Why Use JWTs?

  • Stateless: Server doesn't need to store session data
  • Scalable: Works across multiple servers
  • Mobile-friendly: Easy to use in native apps
  • Cross-domain: Can be used across different domains

Frequently Asked Questions

Common questions about this topic

JWTs are secure for their intended purpose: verifying data integrity and authenticity via signatures. However, the payload is NOT encrypted - anyone can read it. Don't store sensitive data in JWTs. Security depends on proper implementation: strong secrets, short expiration, HTTPS only.

When the 'exp' claim timestamp is in the past, the token is invalid. Servers should reject expired tokens. Clients typically use refresh tokens to get new access tokens, or redirect users to re-authenticate. Never extend expiration on the client side.

Yes, anyone can decode (read) a JWT - it's just Base64. The secret key is only needed to VERIFY the signature (prove it hasn't been tampered with) and to CREATE valid tokens. This is why you should never put sensitive data in JWT payloads.