1. Home
  2. Blog
  3. Software Development

Software Development

What Is JWT? JSON Web Tokens Explained With a Working Example

A JWT lets a server trust a request without looking anything up. Build one from scratch, try to tamper with it and watch it fail, then learn when tokens beat sessions and how to use them safely.

9 min read
What is JWT? JSON Web Tokens explained with a working example

Key takeaways

  • A JWT is a compact, signed token with three parts: header, payload and signature.
  • The signature proves a token has not been changed, so the server can trust it without a lookup.
  • The payload is readable by anyone, so never put secrets in it.
  • Tokens are hard to revoke, so keep them short-lived, and verify them with a trusted library.

After you log in, how does a server know that each later request is really from you? One popular answer is a JSON Web Token, or JWT, usually pronounced “jot”. It is a small, signed piece of data that the client sends with each request, and the server can check it without touching a database.

The fastest way to understand a JWT is to build one and then try to break it. We did that using only Python’s standard library, on Python 3.13, and the output below comes from that run. This code is for learning. In a real application, use a well-maintained library, because the details of verification are easy to get wrong.

What is a JWT?

JWT is an open standard, defined in RFC 7519, for passing claims between two parties as a compact string. A claim is simply a statement, such as “this user’s ID is 42”. Because the token is signed, the receiver can confirm who issued it and that nobody has altered it.

Think of a festival wristband. Staff at the gate check your ticket once and give you a band that is hard to fake. After that, each stall just looks at the band, with no need to phone the ticket office. A JWT works in much the same way for an API.

How JWT login works

  1. The user sends a username and password to the login endpoint.
  2. The server checks them and creates a signed token.
  3. The client stores the token.
  4. Each later request includes it, typically in a header: Authorization: Bearer <token>.
  5. The server verifies the signature and expiry, then reads the claims.

The main benefit is in step 5. The server does not have to look up a session, which is convenient when many services or servers need to check the same token. If you are new to APIs, start with what is an API.

The three parts of a JWT

A JWT looks like random text, but it is three Base64URL-encoded sections separated by dots. Here is one we generated:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzkzNTAwMDAwLCJleHAiOjE3OTM1MDA5MDB9
.7YfUDH_T-iDh8bMmUT8mmKYwOstzT8Ty--DTTAmQGWM

We have added line breaks to make it easier to read. Decoding the first two parts gives plain JSON:

Header:  {"alg":"HS256","typ":"JWT"}
Payload: {"sub":"42","role":"user","iat":1793500000,"exp":1793500900}
Part Contains Purpose
Header Token type and signing algorithm Says how to verify the token
Payload Claims about the user or session The actual information
Signature A hash of the first two parts, using a key Proves integrity and origin

Standard claims

Claim Name Meaning
sub Subject Who the token is about, usually a user ID
iss Issuer Who created the token
aud Audience Who the token is intended for
exp Expiration When the token stops being valid
iat Issued at When it was created
nbf Not before When it starts being valid
jti JWT ID A unique ID for this token

You can also add custom claims, like role. Times are Unix timestamps, in seconds. Keep the payload small, since the token travels with every request.

Build one yourself

Creating a token involves encoding the two JSON parts, and then signing them with a secret using HMAC-SHA256:

import base64, hashlib, hmac, json

SECRET = b"demo-secret-do-not-use-in-production"

def b64url(data):
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def sign(message):
    return b64url(hmac.new(SECRET, message.encode(), hashlib.sha256).digest())

def create_token(payload):
    header = {"alg": "HS256", "typ": "JWT"}
    parts = [
        b64url(json.dumps(header, separators=(",", ":")).encode()),
        b64url(json.dumps(payload, separators=(",", ":")).encode()),
    ]
    message = ".".join(parts)
    return message + "." + sign(message)

Verification works by recalculating the signature, and comparing it with the one in the token. Only someone with the secret can produce a matching one:

def verify_token(token, now):
    header, payload, signature = token.split(".")
    expected = sign(header + "." + payload)
    if not hmac.compare_digest(signature, expected):
        raise ValueError("bad signature")
    claims = json.loads(b64url_decode(payload))
    if claims["exp"] < now:
        raise ValueError("token expired")
    return claims

A valid token returned its claims as expected. compare_digest is used since it runs in constant time, which avoids leaking information through timing differences.

Try to tamper with it

Suppose an attacker decodes the payload, changes "role":"user" to "role":"admin", encodes it again and keeps the old signature. We tried this, along with two other attacks:

Attempt Result
Changed the role to admin bad signature
Used the token 1 second after expiry token expired
Set "alg":"none" and removed the signature bad signature

That last attempt targets a real historic weakness. Some libraries once trusted the token’s own header, so an attacker could simply declare that no signature was needed. Our code always uses one fixed algorithm, which is why it was rejected. In a real library, always specify the algorithms you accept.

Signed, not encrypted

This is the most misunderstood point about JWTs. Our forged token was rejected, yet its contents were still perfectly readable:

{"sub":"42","role":"admin","iat":1793500000,"exp":1793500900}

Base64URL is an encoding, not encryption, and anybody can reverse it with no key at all. The signature stops people from changing the data, but not from reading it. So never put passwords, card numbers or private personal data in a JWT payload. If the contents must be hidden, use encrypted tokens (JWE), or just keep the data on the server.

HS256 vs RS256

Aspect HS256 RS256 or ES256
Type Symmetric Asymmetric
Keys One shared secret A private key signs, a public key verifies
Who can create tokens Anyone holding the secret Only the private key holder
Best for One service, or a small trusted group Many services, third parties, identity providers

With asymmetric signing, other services can verify tokens without being able to mint their own, which limits the damage if one is compromised.

JWT vs sessions

JWTs are often presented as a modern replacement for sessions. In reality, each has trade-offs:

Aspect Server session JWT
Where state lives On the server In the token
Lookup on each request Usually Not needed
Logging out or revoking Easy, delete the session Hard before expiry
Size per request Small ID Larger token (ours was 161 characters)
Across many services Needs shared storage Each can verify it directly
Changing permissions Applies immediately Old token stays valid until expiry

For a traditional server-rendered website, a session cookie is often simpler and safer. JWTs tend to make more sense for APIs consumed by several services, or for mobile clients.

Tip: Do not choose JWT just because it sounds stateless. Many real systems add a denylist or a database check to support logout, which brings back the lookup that JWT was meant to avoid.

Where to store tokens in a browser

Location XSS risk CSRF risk Notes
localStorage High, as scripts can read it Low Simple, but exposed to any injected script
HttpOnly cookie Lower, as scripts cannot read it Needs protection Use Secure and SameSite
In-memory variable Lower Low Lost on refresh, so it needs a refresh flow

Many security guides favour HttpOnly, Secure, SameSite cookies for web apps. Whichever you pick, always use HTTPS. To send a token from JavaScript, see our JavaScript Fetch API tutorial.

Refresh tokens

Short expiry limits the damage from a stolen token, but nobody wants to log in every 15 minutes. The usual solution uses two tokens:

  • Access token: short-lived, such as minutes, and sent with every API request.
  • Refresh token: longer-lived, stored more carefully and used only to obtain new access tokens.

The server keeps track of refresh tokens, so it can revoke them, which gives you a practical logout. Rotating them on each use also helps you detect theft, because a stolen old token gets replayed.

Common security mistakes

  • Decoding without verifying. Reading a payload does not make it trustworthy. Always check the signature.
  • Accepting any algorithm. Set an explicit list of allowed algorithms.
  • Using a weak secret. Short secrets can be cracked offline. Use a long random value, and keep it out of source control.
  • Skipping expiry. Tokens with no exp can work forever if stolen.
  • Not checking iss and aud. Otherwise a token issued for one service may be accepted by another.
  • Trusting stale claims. A role inside a token can be out of date until it expires.
  • Logging tokens. Anyone reading your logs could reuse them.
  • Not testing failure paths. Add tests for expired and modified tokens, as well as valid ones. Our API testing with Postman guide can help.

Final thoughts

A JWT is signed data that a server can trust without a lookup, not a secret container and not an automatic upgrade over sessions. Use short expiry, verify everything with a maintained library, and keep private data out of the payload. To see it for yourself, run a small script like ours, change one character of a token and watch verification fail.

Frequently asked questions

What is a JWT used for?

JWTs are mostly used for authentication and authorization in APIs. After login, a client sends the token with each request, and the server verifies it to identify the user.

Is a JWT encrypted?

Usually not. A standard JWT is signed and encoded, so anyone can read its payload. The signature only prevents changes. Encrypted tokens use a related format called JWE.

How long should a JWT last?

Access tokens are commonly short-lived, often minutes rather than days. Pair them with a refresh token, so users do not have to log in constantly.

Can a JWT be revoked?

Not by itself, as it stays valid until it expires. Revocation requires server-side tracking, such as a denylist, which removes some of the stateless benefit.

Is JWT better than sessions?

Neither is always better. Sessions are simpler to revoke and suit many websites, while JWTs suit APIs and services that need to verify identity independently.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →