Library / Documentation
Introduction to JSON Web Tokens
What a JWT contains and how it is signed and verified.
By Auth0 · jwt.io · Added 2026-10-12
All content belongs to Auth0 / jwt.io. We only link to it and give credit. Report a problem
Learn this doc
About 30 min left. Your work is saved as you go.
What you want from these docs
jwt.io documents a tool you may use. Decide what you want to do with it, then read only what answers that.
Ideas you will meet
- Web Security
- OWASP risks, XSS, CSRF, CORS and secure design.
- OAuth
- Delegated authorization flows for APIs and apps.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Core Concepts: How Things Actually Work · 9 minSSO, OAuth 2.0 and OpenID ConnectHow 'Sign in with Google' works, and the difference between authentication and authorisation.Read here
Two questions, two words
- Authentication: who are you?
- Authorisation: what are you allowed to do?
OAuth 2.0: delegated access
OAuth 2.0 lets a user give an app limited access to their data at another service, without sharing their password. Roles:
- Resource owner: the user.
- Client: the app asking for access.
- Authorization server: issues tokens (for example Google, GitHub).
- Resource server: the API holding the data.
The user grants specific scopes (for example "read my calendar"), and the client receives an access token that is limited to those scopes and expires.
The authorization code flow
100%Figure SDA-CORE-07-1 · Authorization code flow · © forcsguy.com
Important details:
- state: a random value you check on return, which stops attackers forging the callback (CSRF).
- PKCE: a one-time proof that the party exchanging the code is the one that started the flow. Use it for all clients, essential for mobile and single-page apps.
- Register exact redirect URIs and compare them strictly.
OpenID Connect: adding identity
OAuth alone says "this token may call the API", not "this is Jane". OpenID Connect (OIDC) adds an ID token (a signed JWT) with claims about the user: subject id, email, name. To sign someone in, validate the ID token's signature, issuer, audience and expiry.
SSO
With single sign-on, many applications trust one identity provider. The user signs in once; the provider vouches for them to each app. Enterprises use SAML or OIDC for this. Benefits: fewer passwords, central policies like MFA, and one place to revoke access when someone leaves.
Single sign-on means the second application never sees your password. It trusts the sign-in service you already used:
100%Figure SDA-CORE-07-2 · One sign-in, two applications · © forcsguy.com
Common mistakes
- Using the access token as proof of identity instead of validating an ID token.
- Skipping
stateor accepting any redirect URI. - Storing tokens somewhere scripts can read them.
- Requesting more scopes than the feature needs.
More on this site
Related reading
- RFC 6749: The OAuth 2.0 Authorization FrameworkIETFDocumentation
- OAuth 2.0 OverviewOAuth Community · oauth.netDocumentation
- Introduction to JSON Web TokensAuth0 · jwt.ioDocumentation
- System Design 101ByteByteGo · ByteByteGoHqGitHub
Show 6 moreShow fewer
- OAuth Audit Toolbox at IndeedIndeed engineers · IndeedCase Studies
- The Architecture of Open Source ApplicationsVarious authors · aosabook.orgBooks
- Secret Detector: Preventing Secrets in Source Code at YelpYelp engineers · YelpCase Studies
- LevelDBGoogle · GitHubGitHub
- Garbage Collection in Go Application at TwitchTwitch engineers · TwitchCase Studies
- DevOps resource center - Azure DevOpsMicrosoft engineers · MicrosoftBlogs
Real-World Systems · 10 minSecuring a web APIAuthentication, authorisation, input handling and abuse protection: the layers that keep an API safe.Read here
Think in layers
No single control secures an API. Defence comes from several layers, each assuming the others may fail.
100%Figure SDA-RWS-14-1 · API security layers · © forcsguy.com
1. Transport
Use HTTPS everywhere, with modern TLS and HSTS. Never accept credentials over plain HTTP.
2. Authentication: who is calling?
- Users: OAuth 2.0 / OpenID Connect access tokens, or secure session cookies for browsers (see the earlier lessons).
- Machines: API keys or client credentials, stored as hashes, scoped, and rotatable.
- Send credentials in the
Authorizationheader, never in URLs. - Keep token lifetimes short, support revocation, and protect refresh tokens carefully.
- Add multi-factor authentication for sensitive accounts, and protect login endpoints with rate limits.
3. Authorisation: what may they do?
This is where most real API breaches happen.
- Check on every request, on the server, both the action (role or scope) and the specific object. "Is this user logged in?" is not enough; ask "may this user read order 123?" (broken object-level authorisation is the top API risk).
- Apply least privilege: tokens carry only the scopes they need.
- Never rely on the client hiding buttons.
- Do not expose sequential ids as a security measure. Use authorisation checks (random ids only help a little).
4. Input and output
- Validate every input against a schema: types, lengths, ranges, allowed values. Reject unknown fields (prevents mass assignment, where a caller sets fields like
isAdmin). - Use parameterised queries to prevent SQL injection, and encode output to prevent injection into other systems.
- Limit request size and file types, and scan uploads.
- Return only the fields needed (avoid excessive data exposure), and paginate lists.
- Return generic error messages to clients and keep detail in logs, so errors do not leak internals.
100%Figure SDA-RWS-14-2 · Two ways a caller proves who it is · © forcsguy.com
100%Figure SDA-RWS-14-3 · Signing each request with a shared secret (HMAC) · © forcsguy.com
Image: Spanish Coches · CC BY 2.0 · Source · Wikimedia Commons: Peaje - Toll - Péage (5020183265)5. Abuse protection
- Rate limiting per user, key and IP, with stricter limits on expensive or sensitive endpoints.
- Quotas and timeouts; protect against huge queries (depth limits in GraphQL, page size caps).
- Bot and credential-stuffing defences: lockouts, delays, CAPTCHAs, breached-password checks.
6. Webhooks and service-to-service calls
- Sign outgoing webhooks with an HMAC over the body and a timestamp. Receivers verify the signature in constant time, reject old timestamps and handle events idempotently.
- Between services use mutual TLS or signed tokens, and network policies, instead of trusting "internal" traffic.
7. Browsers: CORS and cookies
- Configure CORS with an explicit allow-list of origins. Never reflect any origin with credentials enabled.
- Cookies:
HttpOnly,Secure,SameSite. Protect state-changing requests from CSRF.
An example worth knowing: in 2021 a flaw in a popular Java logging library (Log4Shell) let attackers run their own code simply by getting a crafted string written to a log.
100%Figure SDA-RWS-14-4 · How untrusted text became remote code execution · © forcsguy.com
8. Secrets, data and visibility
- Keep secrets in a secrets manager, not in code or images, and rotate them.
- Encrypt sensitive data at rest, and minimise what you store.
- Log authentication events and authorisation failures (never secrets), and alert on anomalies. Keep an inventory of your APIs so old versions and forgotten endpoints do not stay exposed.
- Keep dependencies patched, and test: security tests, dependency scanning, and periodic penetration testing.
More on this site
Related reading
- MDN: Cross-Origin Resource Sharing (CORS)MDN contributors · MozillaDocumentation
- Introduction to JSON Web TokensAuth0 · jwt.ioDocumentation
- RFC 6749: The OAuth 2.0 Authorization FrameworkIETFDocumentation
- AWS Security BlogAmazon Web Services engineers · Amazon Web ServicesBlogs
Show 6 moreShow fewer
- OWASP Cheat Sheet SeriesOWASP · OWASP FoundationDocumentation
- Google Security BlogGoogle engineers · GoogleBlogs
- How we built rate limiting capable of scaling to millions of domainsCloudflare engineering · CloudflareCase Studies
- OWASP Top 10OWASP · OWASP FoundationDocumentation
- Rate LimitingKeycdn engineers · KeycdnCase Studies
- Scalability and Authentication at TwitchTwitch engineers · TwitchCase Studies
Networking and Web Security Deep Dive · 14 minWeb attacks: XSS, CSRF, injection, SSRF and clickjackingHow each major web attack works in plain terms and the few defences that stop most of them.Read here
Attacker mindset
Most web attacks share one cause: the application trusts input, or trusts the browser, more than it should. The fixes are few and repeatable. This lesson covers five of the most important attacks; the full checklist is in the OWASP lesson. (Authentication and sessions are in the passwords and securing-an-API lessons.)
1. Cross-site scripting (XSS)
What: attacker-controlled text is put into a page and the browser runs it as script. The script runs as your site, so it can read the page, act as the user and steal tokens.
Types: stored (saved in your database, such as a comment), reflected (echoed from a URL parameter), DOM-based (client-side code writes untrusted data into the page unsafely).
// vulnerable: untrusted text inserted as HTML el.innerHTML = comment.text; // <img src=x onerror=stealCookies()> runs! // safe: insert as text el.textContent = comment.text;Defences
- Escape output for its context (HTML, attribute, JavaScript, URL). Modern frameworks (React, Vue and others) escape by default; avoid raw-HTML escape hatches such as
dangerouslySetInnerHTMLorv-htmlwith untrusted data. - If you must allow rich text, sanitise with a well-maintained library and an allow-list.
- A Content Security Policy header limits where scripts can come from, reducing damage if something slips through.
- Mark session cookies HttpOnly so scripts cannot read them.
2. Cross-site request forgery (CSRF)
What: a malicious site makes the victim's browser send a request to your site, and the browser automatically attaches the victim's cookies. If the user is logged in, the action happens (change email, transfer money).
100%Figure SDA-NSD-03-1 · How CSRF works and how a token stops it · © forcsguy.com
Defences
- SameSite cookies (
LaxorStrict) stop browsers sending cookies on most cross-site requests; now the browser default for many cases but set it explicitly. - Anti-CSRF tokens: a random value tied to the session that must accompany state-changing requests.
- Never change state with
GET; check theOriginheader; require re-authentication for sensitive actions. - APIs that use an
Authorizationheader (not cookies) are not vulnerable in the same way, because the browser does not attach it automatically.
3. Injection (SQL, command, and others)
What: input is concatenated into an interpreter's command, so the input changes the command's meaning.
// vulnerable db.query(`SELECT * FROM users WHERE email = '${email}'`); // email = ' OR '1'='1 returns everyone // safe: a parameterised query keeps data and command separate db.query("SELECT * FROM users WHERE email = $1", [email]);Defences
- Parameterised queries / prepared statements for SQL; ORMs do this for normal calls (beware raw-SQL escape hatches).
- Avoid building shell commands from input; use library calls with argument arrays, not strings.
- Validate input against an allow-list of expected formats, and apply least privilege to database accounts (the web app should not be able to drop tables).
- The same pattern applies to NoSQL queries, LDAP, XML and template engines. Rule: never build code or queries by joining strings with untrusted data.
4. Server-side request forgery (SSRF)
What: the app fetches a URL supplied by the user (a preview, an image import, a webhook test). The attacker supplies an internal address; the server, which sits inside your network, fetches it and may return secrets, such as cloud instance credentials from the metadata endpoint, or probe internal services.
Defences
- Prefer an allow-list of destinations; if not possible, block private, loopback and link-local ranges after resolving the name, and re-check on every redirect (and beware of DNS tricks that change the answer between check and use).
- Allow only
httpandhttps; set short timeouts and size limits. - Run fetchers in an isolated network with no route to sensitive services; use cloud settings that require a session token for metadata access.
- Do not return the raw response to the user.
5. Clickjacking
What: your page is loaded in a hidden or disguised frame on an attacker's site, and the user is tricked into clicking buttons they cannot see (like "delete account").
Defences
- Send
Content-Security-Policy: frame-ancestors 'none'(or'self'), and the olderX-Frame-Options: DENY. - Require confirmation for sensitive actions.
One table to remember
Attack Root cause Main defence XSS Untrusted data becomes script in a page Output escaping, CSP, HttpOnly cookies CSRF Browser sends cookies on forged requests SameSite cookies, anti-CSRF tokens Injection Data joined into a command Parameterised queries, validation, least privilege SSRF Server fetches attacker-chosen URLs Allow-lists, block internal ranges, isolation Clickjacking Page framed by another site frame-ancestors / X-Frame-Options Habits
- Defence in depth: assume one layer will fail.
- Validate on the server always; client checks are only for user experience.
- Use framework defaults and keep dependencies updated.
- Log and alert on suspicious input patterns and blocked requests.
- Test: automated scanners, code review checklists and, for important systems, independent penetration tests.
Real-world reading
Related reading
- MDN: Cross-Origin Resource Sharing (CORS)MDN contributors · MozillaDocumentation
- OWASP Cheat Sheet SeriesOWASP · OWASP FoundationDocumentation
- OWASP Top 10OWASP · OWASP FoundationDocumentation
- Introduction to JSON Web TokensAuth0 · jwt.ioDocumentation
Show 6 moreShow fewer
- High Performance Browser NetworkingIlya Grigorik · O'ReillyBooks
- RFC 9114: HTTP/3IETFDocumentation
- Building Secure and Reliable SystemsGoogle engineers · O'Reilly / GoogleBooks
- RFC 6749: The OAuth 2.0 Authorization FrameworkIETFDocumentation
- Syscall Auditing at Scale at SlackScale at Slack engineers · Scale at SlackCase Studies
- MySQL High Availability at GitHubGitHub Engineering · GitHubCase Studies
- Escape output for its context (HTML, attribute, JavaScript, URL). Modern frameworks (React, Vue and others) escape by default; avoid raw-HTML escape hatches such as
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Introduction to JSON Web Tokens.
Warm upGet the vocabulary first.
Documentation
RFC 6749: The OAuth 2.0 Authorization Framework
The standard defining OAuth 2.0 roles and flows.
IETFAdvanced
Documentation
OWASP Top 10
The standard awareness list of the most critical web application security risks.
OWASP FoundationBeginner
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs
AWS Security Blog
Amazon GuardDuty Extended Threat Detection correlates weak GuardDuty signals into a single, critical-severity attack sequence finding when their composition crosses a threshold of credibility. On May 20, 2026, the ser...
Amazon Web ServicesIntermediate
Blogs
Google Security Blog
Google's security blog: news and updates on security topics, such as new Android protections.
GoogleIntermediate
See it in another companyThe same ideas, a different system.
Case Studies · Read here
OAuth Audit Toolbox at Indeed
Integrating third party apps with GSuite can be risky. Indeed's OAudit Toolbox allows you to educate your users and improve application security.
IndeedIntermediate
Case Studies · Read here
Clock Skew when Syncing Password Payloads at Drobbox
How Dropbox Passwords fixed sync errors from clock skew by replacing a two-way timestamp merge with a three-way merge against a base payload.
DrobboxIntermediate
Read the codeSee how it looks when it is real.
GitHub
System Design 101
Visual cheat sheets explaining complex systems in simple terms.
ByteByteGoHqBeginner
Keep learning
Loading community…