Webgigo
We use Google Analytics to improve the site. Do you consent to anonymous analytics?
Developer ToolsJuly 7, 2026 14 min read

What Is JWT? Understanding JSON Web Tokens

JWTs power login sessions across countless apps and APIs, but few people outside of development fully understand how they work. Here's a clear, practical breakdown of JSON Web Tokens.

What Is JWT? Understanding JSON Web Tokens

Introduction

If you've ever logged into a website and stayed logged in as you clicked around, there's a good chance a JWT was quietly working behind the scenes to make that possible. JWT, short for JSON Web Token, is one of the most widely used methods for handling authentication and secure data exchange on the modern web. It shows up in login systems, API requests, and mobile apps everywhere, yet many developers use it daily without fully understanding what's actually inside one or why it's structured the way it is. This guide breaks down exactly what a JWT is, how it's built, how it works in a real authentication flow, and the mistakes that can turn a useful security tool into a genuine vulnerability if handled carelessly.


What Is a JWT?

A JWT (JSON Web Token) is a compact, self-contained way of securely transmitting information between two parties as a JSON object. It's commonly used to represent claims — statements about a user or entity — in a format that can be verified and trusted because it's digitally signed. The key idea behind a JWT is that it's stateless: all the information needed to verify who a user is (or what permissions they have) is contained within the token itself, rather than requiring the server to look up a session stored in a database every time. A JWT looks like a long string of characters separated by two periods, like this structure: `` header.payload.signature ` Each of those three parts is Base64URL-encoded and serves a distinct purpose, which we'll break down in detail below.

Why It Matters

For developers: JWTs are foundational to modern authentication systems, especially in single-page applications, mobile apps, and microservices architectures where a traditional server-side session isn't practical. For API providers and platform builders: JWTs allow secure, stateless communication between services, reducing the need for constant database lookups to verify every request. For security-conscious teams: Understanding how JWTs are signed, verified, and potentially misused is essential for building systems that are actually secure rather than just appearing secure. For students and career changers learning backend development: JWT-based authentication appears in an enormous number of real-world job requirements, tutorials, and frameworks, making it a genuinely valuable concept to understand deeply rather than just copy-pasting code for.

A Practical Example

When you log into an application, the server verifies your username and password, then issues a JWT containing your user ID and perhaps your role (like "admin" or "member"). Your browser or app stores that token and sends it along with every subsequent request. The server can verify the token's signature instantly, confirming it hasn't been tampered with, without needing to check a session database on every single request — making the system faster and easier to scale.

Key Concepts

The Three Parts of a JWT

Header The header typically specifies the token type (JWT) and the signing algorithm used (commonly HMAC SHA256 or RSA). It's a small JSON object, Base64URL-encoded. Payload The payload contains the actual claims — the data being transmitted, such as a user ID, role, or expiration time. This part is also JSON, Base64URL-encoded, but importantly, it is not encrypted. Anyone who has the token can decode and read the payload; the signature only proves it hasn't been altered, not that it's confidential. Signature The signature is created by combining the encoded header, encoded payload, a secret key (or private key for asymmetric algorithms), and running them through the specified signing algorithm. This signature is what allows the server to verify the token's authenticity and integrity.

Claims

Claims are the individual pieces of information stored in the payload. There are three categories: * Registered claims — standardized, optional claims like
exp (expiration time), iss (issuer), and sub (subject). * Public claims — custom claims defined by those using JWTs, ideally registered in the IANA JSON Web Token Registry to avoid collisions. * Private claims — custom claims agreed upon between parties for their specific application, not intended for public standardization.

Symmetric vs Asymmetric Signing

* Symmetric signing (like HMAC SHA256) uses a single secret key to both sign and verify the token. Both parties must share this secret securely. * Asymmetric signing (like RSA or ECDSA) uses a private key to sign the token and a corresponding public key to verify it. This allows the public key to be shared openly, since it can only verify tokens, not create new ones.

JWTs Are Not Encrypted by Default

This is one of the most misunderstood aspects of JWTs. A standard JWT (using JWS, JSON Web Signature) is signed, not encrypted — meaning its contents are readable by anyone who has the token, even without the secret key. If truly confidential data needs to be included, a JWE (JSON Web Encryption) variant or a separate encryption layer is required.

How It Works

How JWT Authentication Typically Works

  • A user submits their login credentials to the server.
  • The server verifies the credentials against its database.
  • If valid, the server creates a JWT containing relevant claims (like user ID and role) and signs it using a secret or private key.
  • The server sends the JWT back to the client, which stores it (commonly in local storage, a cookie, or in-memory).
  • For subsequent requests, the client includes the JWT, typically in an Authorization header using the format Bearer .
  • The server verifies the token's signature and checks its expiration before processing the request, without needing to query a session database.

How Signature Verification Works

  • The server takes the received token's header and payload sections.
  • It recomputes the signature using the same algorithm and secret (or public key) originally used to sign it.
  • It compares this recomputed signature against the signature included in the token.
  • If they match, the token is considered valid and unaltered. If they don't match, the token is rejected.

Step-by-Step Guide

How to Decode a JWT (Without Verifying It)

  • Split the JWT string into its three parts using the periods as separators.
  • Base64URL-decode the header section to view the algorithm and token type.
  • Base64URL-decode the payload section to view the claims (user data, expiration, etc.).
  • Note that decoding does not verify the token — it only reveals its readable contents.

How to Implement Basic JWT Authentication (Conceptual Overview)

  • Choose a JWT library appropriate for your backend language or framework.
  • On successful login, generate a JWT containing necessary claims (user ID, role, expiration).
  • Sign the token using a securely stored secret or private key.
  • Send the token to the client and instruct it to include the token in future request headers.
  • On each protected request, verify the token's signature and check that it hasn't expired before granting access.
  • Implement token refresh logic if using short-lived access tokens alongside longer-lived refresh tokens.

How to Test a JWT Implementation

  • Generate a token through your login flow and confirm it decodes to the expected claims.
  • Attempt to access a protected endpoint with a valid token and confirm access is granted.
  • Attempt to access the same endpoint with an expired or tampered token and confirm access is denied.
  • Verify that sensitive data is never placed directly in the payload without additional encryption, since it is not encrypted by default.

Real-World Examples

A single-page application (SPA): A React or Vue app stores a JWT after login and attaches it to every API request, allowing the backend to verify the user's identity without maintaining server-side session state. A mobile app calling multiple backend services: JWTs allow different microservices to verify a user's identity independently, without each service needing direct access to a shared session database. A third-party API integration: Some APIs issue JWTs as access tokens, allowing developers to authenticate requests without repeatedly sending username and password credentials. An enterprise system with role-based access control: JWT payloads can include role claims (like "admin" or "editor"), allowing the backend to make authorization decisions directly from the token's contents. A team debugging a login issue: Developers frequently decode JWTs during debugging to inspect claims and expiration times, without needing to access the server's signing secret.

Benefits

* Enables stateless authentication, reducing the need for server-side session storage * Scales well across distributed systems and microservices architectures * Self-contained — all necessary claims travel with the token itself * Supported by virtually every major programming language and framework * Can include custom claims tailored to an application's specific authorization needs * Reduces database load compared to traditional session-based authentication for every request

Common Mistakes

* Storing sensitive data in the payload, assuming it's encrypted. JWT payloads are only signed, not encrypted by default, meaning anyone with the token can read the contents. * Using a weak or easily guessable secret key for signing. A compromised secret allows attackers to forge valid tokens. * Not setting an expiration time. Tokens without an
exp claim can remain valid indefinitely, increasing security risk if a token is ever compromised. * Storing JWTs insecurely on the client. Storing tokens in local storage can expose them to cross-site scripting (XSS) attacks; secure, HTTP-only cookies are often a safer alternative depending on the application's architecture. * Failing to implement token revocation. Since JWTs are stateless and self-verifying, revoking a specific token before its expiration requires additional infrastructure (like a blocklist), which is often overlooked. * Confusing JWTs with session tokens conceptually. JWTs and traditional session IDs solve similar problems differently, and treating them interchangeably without understanding the trade-offs can lead to design mistakes.

Best Practices

* Always set a reasonable expiration time (
exp claim) on JWTs, and use shorter-lived access tokens paired with longer-lived refresh tokens where appropriate. * Never store sensitive or confidential data directly in a JWT payload unless using proper encryption (JWE) in addition to signing. * Use strong, securely stored secret keys for symmetric signing, or properly managed key pairs for asymmetric signing. * Store JWTs on the client using secure methods appropriate to your application's architecture, considering the trade-offs between local storage and HTTP-only cookies. * Validate the token's signature and expiration on every protected request — never trust a token's claims without verification. * Implement a token revocation strategy if your application requires the ability to invalidate specific tokens before they naturally expire.

Comparison

JWT vs Traditional Session-Based Authentication

AspectJWTSession-Based Authentication
---------
State storageStateless (data stored in the token)Stateful (session stored server-side)
ScalabilityScales well across distributed systemsRequires shared session storage across servers
RevocationDifficult without additional infrastructureSimple (delete the session record)
Data exposurePayload is readable if decoded (not encrypted)Session data stays server-side, not exposed to client
Typical use caseAPIs, microservices, mobile apps, SPAsTraditional server-rendered web applications

JWS vs JWE

AspectJWS (JSON Web Signature)JWE (JSON Web Encryption)
---------
PurposeVerifies integrity and authenticityEncrypts the actual contents
Payload readabilityReadable by anyone with the tokenNot readable without decryption key
Common useStandard JWT authenticationSensitive data requiring confidentiality

Frequently Asked Questions

1. Is a JWT encrypted? Not by default. A standard JWT (JWS) is signed to verify authenticity and integrity, but its payload is readable by anyone who has the token. True encryption requires a JWE variant or an additional encryption layer. 2. Can a JWT be tampered with? The payload itself can technically be altered by anyone who has the token, but doing so invalidates the signature, causing the server to reject the modified token during verification. 3. How long should a JWT stay valid? This depends on your application's security requirements, but shorter-lived access tokens (minutes to hours) paired with longer-lived refresh tokens are a common, more secure approach than issuing very long-lived tokens. 4. What's the difference between an access token and a refresh token? An access token is typically short-lived and used to authenticate individual requests. A refresh token is longer-lived and used specifically to obtain new access tokens without requiring the user to log in again. 5. Can I revoke a JWT before it expires? Not natively, since JWTs are stateless and self-verifying. Implementing revocation typically requires additional infrastructure, such as a token blocklist checked during verification. 6. Is it safe to store a JWT in local storage? It's a common practice, but it carries some risk of exposure through cross-site scripting (XSS) attacks. Many security-conscious applications instead use secure, HTTP-only cookies, depending on the specific application's architecture and threat model. 7. What algorithm is used to sign a JWT? Common algorithms include HMAC SHA256 (symmetric) and RSA or ECDSA (asymmetric), specified in the token's header. 8. Can anyone decode a JWT? Yes, anyone with the token can decode the header and payload, since they are only Base64URL-encoded, not encrypted. Only the signature verification requires the secret or private key. 9. Why use JWT instead of traditional sessions? JWTs are particularly useful in distributed systems, microservices, and mobile applications where maintaining shared server-side session state across multiple servers would be more complex or less scalable. 10. What happens if my JWT secret key is compromised? An attacker with your signing secret could forge valid tokens, effectively impersonating any user. This is why securely storing and rotating signing secrets is a critical security practice. 11. Can a JWT contain any data I want? Technically yes, but best practice is to keep payloads small and avoid including sensitive or unnecessary data, since the payload is not encrypted and larger tokens increase the size of every request that includes them.

Troubleshooting

My JWT verification is failing even though the token looks correct. Double-check that the same secret key (or correct public key, for asymmetric signing) is being used for verification as was used for signing. A mismatch will always cause verification to fail. My decoded JWT payload looks fine, but the server rejects it. Check the token's expiration (
exp` claim) — an expired token will fail verification even if its structure and signature are otherwise valid. Users are getting logged out unexpectedly. This is often related to a short expiration time on the access token without a properly implemented refresh token flow to silently obtain a new one. Sensitive data appears in a decoded JWT. This indicates the payload includes information that should not be stored in plaintext. Remove sensitive claims and rely on server-side lookups instead, or implement JWE for true encryption if the data must travel within the token. I can't figure out how to revoke a specific user's token. Since JWTs are stateless, implement a server-side blocklist (checked during verification) or reduce the token's expiration time to limit the window of exposure if immediate revocation is required. My asymmetric JWT verification fails after rotating keys. Ensure the correct public key corresponding to the private key used for signing is being used for verification, and confirm your key rotation process updates all verifying services consistently.

Related Tools

If you work with authentication and structured data regularly, these free webgigo tools can help: * JSON Formatter — Format and inspect decoded JWT payloads for easier readability. * Base64 Encoder — Understand how JWT header and payload segments are encoded and decoded. * URL Encoder — Useful when working with tokens passed as URL query parameters. * Password Generator — Generate strong secret keys for signing JWTs securely.

Conclusion

A JWT is, at its core, a compact and verifiable way to pass trusted information between a client and a server without requiring constant server-side lookups. Understanding its three-part structure — header, payload, and signature — along with the crucial distinction between signing and encryption, is what separates a secure implementation from a vulnerable one. Whether you're building your first login system or debugging an authentication issue in a production API, knowing exactly what's inside a JWT, how it's verified, and where the common pitfalls lie will make you significantly more effective at building and troubleshooting modern authentication systems. Ready to inspect or work with structured token data? Try webgigo's free JSON Formatter to view and format decoded JWT payloads clearly — no software downloads required.

Related Posts