# JWT

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/jwt

## Quick definition

A JWT is like a digital ID card that proves who you are and what you're allowed to do. When you log into a website, the server gives you a JWT instead of making you type your password again on every page. You send this token with each request, and the server checks it to verify your identity without needing to look up your password each time.

## Simple meaning

Think of a JWT as a special, tamper-evident digital badge that you get after proving your identity to a system. When you log into a website, the server creates this JSON Web Token and hands it to you. This token contains a small amount of information about you, like your user ID and what permissions you have. The token is digitally signed by the server using a secret key, which means if anyone tries to change the information inside the token, the signature will break and the server will know something is wrong.

A useful everyday analogy is a hand stamp at a concert. When you show your ticket at the entrance, the staff stamps your hand with an invisible ink that glows under blacklight. As you walk around the concert, security can shine a blacklight on your hand to see the stamp. They don't need to call the main ticket office every time you move between areas. The stamp itself proves you've paid. Similarly, a JWT proves you have already authenticated. The server issues this token once, and you present it with every subsequent request, avoiding the need to log in repeatedly.

The key advantage of JWT is that it is stateless. The server does not need to store session information in a database. All the necessary information is inside the token itself. This makes JWTs very efficient for modern applications that run on many servers or scale to millions of users. However, because the token contains readable information (though it is base64 encoded and not encrypted by default), you must never put sensitive data like passwords or credit card numbers inside a JWT unless you also encrypt the whole token. In IT security, JWTs are most commonly used for authentication (logging in) and authorization (what you can do after logging in). Understanding JWTs is important because they appear in many modern web frameworks, API security implementations, and identity protocols like OAuth 2.0 and OpenID Connect.

## Technical definition

A JSON Web Token (JWT) is an open standard defined by RFC 7519. It represents claims between two parties in a compact, URL-safe format. The token consists of three parts separated by dots: a header, a payload, and a signature. Each part is Base64Url-encoded. The header usually contains the type of token (which is JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA. The payload contains the claims, which are statements about an entity (typically the user) and additional data. There are registered claims like iss (issuer), exp (expiration time), sub (subject), aud (audience), and iat (issued at). Custom claims can also be included. The signature is created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header. The signature is used to verify that the token hasn't been altered and to confirm the identity of the sender.

In practice, JWTs are used in two main scenarios: authentication and information exchange. In authentication, after a user logs in successfully, the server generates a JWT and sends it to the client. The client stores this token (usually in local storage or an HTTP-only cookie) and sends it in the Authorization header of subsequent requests using the Bearer scheme: Authorization: Bearer <token>. The server then validates the token's signature and checks the expiration time before granting access. This eliminates the need for server-side session storage, making applications easier to scale horizontally across multiple servers.

For information exchange, JWTs can securely transmit data between parties. Because the signature is created using a secret key known only to the sender and receiver, the recipient can verify that the content hasn't been tampered with. However, note that the payload is only base64 encoded, not encrypted. Anyone who intercepts the token can decode the payload and read its contents. For this reason, sensitive information should never be placed in the payload unless additional encryption (JWE) is used.

Real-world IT implementations often use JWTs as access tokens in OAuth 2.0 and OpenID Connect workflows. For example, when a user authenticates with Google, Google issues an ID token in JWT format. The relying party (a website) can decode the JWT to get the user's email address and profile information without needing to call Google's API again. JWTs are also used in microservices architectures, where a gateway service validates a token and propagates the user context to downstream services. Common pitfalls include misconfiguring the algorithm to allow 'none' as a signature algorithm, failing to properly validate the token's expiration time, and storing the token insecurely on the client side, which can lead to XSS attacks.

## Real-life example

Imagine you are at a large office building that requires visitors to check in at the front desk. When you arrive, you show your ID to the security guard. The guard verifies your identity, checks that you have a meeting scheduled, and then gives you a visitor badge. This badge has your name, a photo, and a barcode that encodes the departments you are allowed to visit. The badge is also laminated and has a holographic seal that is hard to forge. As you move through the building, you show your badge at each secure door. The security scanners read the barcode and verify the hologram. They don't need to call the front desk again because the badge itself contains all necessary information and is tamper-evident.

In this analogy, the visitor badge is the JWT. The front desk is the authentication server that issues the token after verifying your credentials. The barcode and hologram are the signature, which ensures the badge has not been altered. The departments listed on the badge are the claims (permissions). Each secure door scanner is a resource server that validates the token before granting access. The key point is that the badge is self-contained. The door doesn't have to call the front desk for every check. Similarly, a JWT eliminates the need for the server to query a database for each request, making systems faster and more scalable.

Now imagine that someone tries to change the departments on their badge by scratching out one name and writing another. When they try to use the badge, the scanner will detect that the hologram doesn't match the changed information, and the door will stay locked. This is exactly what happens when someone tries to tamper with a JWT payload. The server recomputes the signature using the altered payload, sees that it doesn't match the signature on the token, and rejects the request. This security feature is critical in protecting API endpoints and user sessions.

## Why it matters

JWTs matter because they solve a fundamental problem in modern web development: how to maintain user identity and permissions across many requests without relying on server-side sessions. Traditional session-based authentication stores session data in memory or a database. For applications that need to scale to thousands or millions of users, this approach becomes expensive and complex. JWTs are stateless, which means any server can verify a token without needing to share session data with other servers. This makes horizontal scaling straightforward and efficient.

In practical IT contexts, JWTs are everywhere. When you log into a single-page application (SPA) like Gmail or Trello, the backend issues a JWT. The SPA stores this token and sends it with every API call. Without JWTs, the SPA would need to manage cookies and session IDs, which can be more complex and less secure in cross-origin scenarios. JWTs also play a central role in API security. When you build an API that serves mobile apps, third-party developers, or front-end applications, using JWTs allows you to decouple authentication from the API logic.

Another reason JWTs matter is their role in identity federation. Protocols like OpenID Connect are built on top of JWT. When you use "Sign in with Google" or "Sign in with Facebook," the identity provider (Google, Facebook) issues a JWT to the relying party (the website you are visiting). This JWT contains claims about your identity, such as your email address and name. The website can trust this token because it is signed by the identity provider. This eliminates the need for the website to store and manage passwords, reducing security risks for both the website and the user.

From a career perspective, understanding JWTs is essential for any IT professional working with web applications, APIs, cloud services, or identity management. Many certification exams, from CompTIA Security+ to AWS Certified Solutions Architect, include questions about token-based authentication and how JWT fits into broader security architectures. Misunderstanding JWTs can lead to serious vulnerabilities, such as accepting tokens with algorithm 'none' or failing to validate token expiration, which could allow an attacker to forge tokens and gain unauthorized access.

## Why it matters in exams

JWTs appear in several major IT certification exams, though the depth of coverage varies. For CompTIA Security+ (SY0-601 and SY0-701), JWTs are part of domain 3.0 (Implementation) under authentication and authorization concepts. The exam expects you to understand the difference between token-based and session-based authentication, the structure of a JWT (header, payload, signature), and common security concerns like not storing sensitive data in the token. You may see multiple-choice questions asking which type of token is best for stateless authentication or what component of a JWT prevents tampering. The Security+ exam does not require you to generate or parse JWTs, but you should know the standard terminology and the security implications.

For AWS Certified Solutions Architect (SAA-C03), JWTs are relevant to identity and access management. Questions may involve how Amazon Cognito issues JWT tokens for user authentication, how to use JWT for authorizing API Gateway requests, or how to validate JWT from external identity providers. The exam might present a scenario where an application uses a JWT for authorization across multiple microservices, and you need to choose the best architecture for token validation (e.g., using a Lambda authorizer or a centralized validation service). Understanding the role of JWT in OAuth 2.0 and OpenID Connect will help you answer these questions correctly.

For the CISSP exam, JWTs appear in the Identity and Access Management (IAM) domain. The focus is on trust models, federation, and token-based authentication. You may be asked to compare JWT with SAML assertions. Both are used for identity federation, but JWT is more compact and better suited for mobile and web APIs. The CISSP exam expects you to know the strengths and limitations of each. For example, SAML uses XML which is heavier, while JWT uses JSON which is lighter. The exam might also cover the differences between signed (JWS) and encrypted (JWE) tokens.

For the CCSP (Certified Cloud Security Professional), JWTs appear in the context of cloud application security and identity federation. Questions may involve how to securely distribute and validate JWTs in a multi-cloud environment, or how to use JWT for cross-domain identity propagation. The exam emphasizes the need to validate token expiration, issuer, and audience to prevent token reuse or injection attacks.

In all these exams, common question types include: identifying the correct order of JWT parts, understanding why the payload should not contain secrets, recognizing attacks like JWT algorithm confusion, and selecting the appropriate token type for a given scenario. You will not be asked to write code, but you should be able to interpret a JWT header and payload in a question. Having a clear mental model of how JWTs work, along with their security best practices, is essential for scoring well on these exam objectives.

## How it appears in exam questions

Exam questions about JWTs often fall into three categories: scenario-based, configuration-based, and troubleshooting-based. In scenario-based questions, you are given a description of an application architecture and asked which authentication method is most suitable. For example: 'A company is migrating from a monolithic web application to a microservices architecture. They need a stateless authentication mechanism that allows each microservice to verify user identity without querying a central database. Which token type should they use?' The correct answer is JWT, and the key reasoning is statelessness and self-containment.

Configuration-based questions might present a JSON snippet of a JWT header and payload and ask you to identify an issue. For instance: 'Given this JWT header: {"alg":"none","typ":"JWT"}. Which security vulnerability does this represent?' The answer is that the algorithm 'none' allows the token to be accepted without any signature verification, making it trivial for an attacker to forge arbitrary tokens. Another common question: 'In the payload below, what is the primary security concern? {"sub":"1234567890","name":"John Doe","iat":1516239022,"password":"letmein"}' The issue is that a password is included in the payload, which is only base64 encoded and not encrypted, exposing it to anyone who can read the token.

Troubleshooting questions might involve a scenario where users are intermittently getting 401 Unauthorized errors when accessing an API. The question might say: 'Users log into an application and receive a JWT with an expiration time of 1 hour. After 50 minutes, some users report being logged out unexpectedly. What is the most likely cause?' The answer could be that the server's clock and the client's clock are out of sync, or that the token's issued at time (iat) is validated and the server's clock skew tolerance is too low. Another troubleshooting pattern: 'An API gateway is configured to validate JWTs signed with RSA. After a key rotation, all tokens are rejected. What is the likely issue?' The problem might be that the gateway still has the old public key and does not have the new public key, or that the algorithm in the header changed and the gateway is not configured to accept it.

You may also see questions about the difference between JWT and opaque tokens. For example: 'An API uses opaque tokens (random strings) that must be looked up in a database for validation. The team wants to reduce database load. Which approach should they take?' The answer is to switch to JWT, which can be validated locally without a database round trip. Conversely, a question might highlight a disadvantage of JWT, such as the inability to revoke a token immediately without maintaining a blacklist, which is a consideration in some security architectures.

Finally, exam questions sometimes ask about the correct placement of JWTs in HTTP requests. A typical question: 'Where should a client include a JWT when making an authenticated API request?' The correct answer is the Authorization header with the Bearer scheme. Distractors might include the request body, the URL query string, or a custom header. Placing tokens in the URL is insecure because URLs are often logged or cached, while placing them in the request body is not standard for REST APIs.

## Example scenario

A healthcare portal allows doctors to view patient records. The portal is built as a single-page application that communicates with a REST API. When a doctor logs in using their username and password, the authentication server verifies the credentials. If valid, the server creates a JWT containing the doctor's user ID, their role (e.g., 'doctor' or 'admin'), and an expiration time of 30 minutes. The server signs this JWT with a secret key known only to the authentication server. This signed JWT is then sent back to the browser.

The browser stores the JWT in local storage. When the doctor requests a list of patients, the JavaScript code attaches the JWT to the Authorization header of the HTTP request. The API gateway receives the request, extracts the JWT, and validates the signature using the same secret key. It checks that the token is not expired and that the doctor's role has permission to view patient records. If everything is valid, the API returns the requested data. If the JWT is expired or invalid, the API returns a 401 Unauthorized response, and the browser redirects the doctor to the login page.

Now suppose an attacker intercepts the JWT from the network traffic. The attacker can decode the base64 payload and see the doctor's user ID and role, but cannot modify the token because they do not have the secret key needed to create a valid signature. If the attacker tries to change the role from 'doctor' to 'admin' and then send the modified token, the API will recompute the signature and see that it does not match. The request will be rejected. This is how JWT ensures the integrity of the data, even though the payload is not hidden.

In this scenario, the stateless nature of JWT means the API does not need to query a database to check the doctor's session. This reduces latency and allows the API servers to be scaled independently. However, the doctor's token will only be valid for 30 minutes. If the doctor is still actively using the portal after 30 minutes, they will need to obtain a new token, either by re-authenticating or by using a refresh token that can swap for a new access token. This refresh token pattern is common in real-world implementations and adds an extra layer of security while maintaining user convenience.

## Common mistakes

- **Mistake:** Storing JWT in localStorage without proper XSS protection.
  - Why it is wrong: LocalStorage is accessible to any JavaScript running on the same origin. If an attacker successfully injects malicious JavaScript via an XSS vulnerability, they can steal the JWT and impersonate the user indefinitely until the token expires.
  - Fix: Store JWT in an HTTP-only cookie, which cannot be accessed by JavaScript. Alternatively, use a short token lifetime and implement content security policies to reduce XSS risk.
- **Mistake:** Including sensitive data like passwords or credit card numbers in the JWT payload.
  - Why it is wrong: The payload is only base64 encoded, not encrypted. Anyone with access to the token can decode it and read the payload. This is a massive security and compliance violation.
  - Fix: Never put secrets in the JWT payload. If you need to transmit sensitive data, use JWE (JSON Web Encryption) to encrypt the entire token, or pass that data via other secure channels.
- **Mistake:** Using algorithm 'none' in the JWT header or accepting tokens with 'none' algorithm.
  - Why it is wrong: Specifying 'none' means the token has no signature. An attacker can create arbitrary tokens with any payload and set the algorithm to 'none'. If the server does not reject these tokens, it will trust forged identities.
  - Fix: Always validate the algorithm. Never accept 'none' in production. Configure your JWT library to only accept signed tokens (HS256, RS256, etc.) and explicitly whitelist allowed algorithms.
- **Mistake:** Failing to validate the token expiration time.
  - Why it is wrong: Without expiration validation, an attacker who obtains a valid token (even an old one) can use it indefinitely. This is a fundamental security control that must not be omitted.
  - Fix: Always check the exp claim (expiration time) in the payload. Reject any token whose exp is in the past. Also consider validating the iat and nbf claims for additional protection.

## Exam trap

{"trap":"A question asks: 'What is the primary advantage of using a JWT over a session ID stored in a cookie?' The trap answer is 'JWTs are encrypted, so they are more secure.'","why_learners_choose_it":"Learners often assume that because JWT is used for authentication, it must be encrypted. The term 'token' sounds secure, and the base64 encoding looks like gibberish, so they incorrectly think it is encrypted.","how_to_avoid_it":"Remember that base64 is encoding, not encryption. Anyone can decode a JWT payload. The actual security comes from the signature, which prevents tampering but does not hide the contents. Encrypted JWTs exist (JWE) but are not the default. The real advantage of JWT is statelessness and scalability, not secrecy."}

## Commonly confused with

- **JWT vs SAML Assertion:** SAML is an older, XML-based standard for exchanging authentication and authorization data between parties. It is heavier and more verbose than JWT. SAML uses XML signatures and relies heavily on the browser for redirect-based flows. JWT is more compact, uses JSON, and is better suited for modern web APIs and mobile apps. SAML is commonly used in enterprise single sign-on, while JWT is prevalent in OAuth 2.0 and OpenID Connect. (Example: If you are building a modern REST API, you would choose JWT. In a large corporate environment with legacy systems, you might encounter SAML.)
- **JWT vs OAuth 2.0 Access Token:** OAuth 2.0 is a framework for authorization, and it can issue tokens in different formats, including opaque tokens or JWT. Not all OAuth 2.0 access tokens are JWTs. An opaque token is a random string that must be validated by calling an introspection endpoint. A JWT is self-contained and can be validated locally. So JWT is a type of token that can be used within the OAuth 2.0 framework, but it is not the same as the OAuth protocol itself. (Example: When you log into a website using Google, the access token you get might be a JWT, but it could also be an opaque string. The protocol is OAuth 2.0, the token format is JWT.)
- **JWT vs Cookie-based Session:** In a traditional session-based system, the server stores session data in memory or a database. The client receives a random session ID stored in a cookie. On each request, the server looks up the session by ID. With JWT, no server-side storage is needed; all information is inside the token. Sessions are stateful; JWT is stateless. Sessions are easier to revoke immediately; JWT revocation requires additional infrastructure like a token blacklist. (Example: In a session-based system, if you clear your cookies, you are logged out. In a JWT-based system, if the token is stored in a cookie, clearing cookies also logs you out, but if stored in local storage, you stay signed in until the token expires.)

## Step-by-step breakdown

1. **User Authentication Request** — The client sends the user's credentials (e.g., username and password) to the authentication server. This is typically done over HTTPS to protect the credentials in transit.
2. **Server Verifies Credentials** — The authentication server checks the credentials against its user store (database, LDAP, etc.). If correct, it proceeds to create a JWT. If incorrect, it returns an error response.
3. **Create the JWT Header** — The server creates the header JSON object specifying the token type (JWT) and the signing algorithm (e.g., HS256 or RS256). This header is then base64url encoded.
4. **Create the JWT Payload** — The server creates the payload JSON object containing claims such as sub (subject/user ID), iat (issued at), exp (expiration time), and any custom claims like roles or permissions. This payload is also base64url encoded.
5. **Sign the Token** — The server concatenates the encoded header and payload with a dot separator. It then creates a digital signature using the specified algorithm and a secret key (or private key for asymmetric algorithms). The signature is also base64url encoded.
6. **Assemble the JWT** — The server concatenates the encoded header, encoded payload, and encoded signature with dots to form the complete JWT string. This string is then sent back to the client as part of the authentication response.
7. **Client Stores and Sends the JWT** — The client (browser, mobile app) stores the JWT securely. On subsequent requests to protected resources, the client includes the JWT in the Authorization header as Bearer token.
8. **Server Validates the JWT on Each Request** — The resource server receives the request, extracts the JWT from the header, splits it into its three parts, decodes the header to get the algorithm, decodes the payload, and then verifies the signature using the appropriate secret or public key. It also checks claims like exp and aud.
9. **Grant or Deny Access** — If the signature is valid and all claims pass (token not expired, audience matches, issuer trusted), the server processes the request and returns the protected resource. If validation fails, it returns a 401 Unauthorized status.

## Practical mini-lesson

In real-world IT environments, implementing JWT correctly requires careful consideration of several practical factors. First, you must choose between symmetric (HMAC) and asymmetric (RSA, ECDSA) signing algorithms. Symmetric algorithms use a single shared secret key for both signing and verification. This is simpler but means any service that can verify the token also can create valid tokens, so the secret must be kept extremely secure and only shared among trusted services. Asymmetric algorithms use a private key for signing and a public key for verification. This allows multiple services to verify tokens without having the private key, which is ideal for microservices architectures. The trade-off is performance: asymmetric signing and verification are computationally more expensive.

Second, key management is critical. If you use symmetric keys, you need a secure way to distribute the secret to all services that need to validate tokens. If you use asymmetric keys, you must securely store the private key and distribute the public key to verification services. When you rotate keys (which you should do regularly), you need to handle the transition period gracefully. For example, you can keep the old public key available for a short time to validate tokens issued before the rotation, while new tokens are signed with the new private key.

Third, token lifetime and refresh strategies are essential. A JWT cannot be revoked once issued (unless you maintain a blacklist, which defeats the stateless advantage). Therefore, access tokens should have a short lifetime, typically 15 to 60 minutes. Refresh tokens, which have a longer lifetime (days or months), can be stored securely and used to obtain new access tokens without requiring the user to re-authenticate. The refresh token itself can be revoked server-side, providing a way to terminate the user's session if needed.

Fourth, you must consider where to store the JWT on the client side. Storing it in localStorage is simple but vulnerable to XSS. Storing it in an HTTP-only cookie with Secure and SameSite flags is more secure against XSS but introduces complexity with CSRF protection. The choice depends on your security requirements and threat model. For high-security applications, using a combination of a short-lived JWT stored in memory (not persisted) and a refresh token stored in an HTTP-only cookie is a common pattern.

Fifth, error handling and logging are important. When token validation fails, the server should return a standard HTTP 401 status with a clear error message (e.g., 'expired token', 'invalid signature'), but avoid revealing too much information that could help an attacker. Logging failed validation attempts can help detect brute-force attacks or token theft. Implementation errors are common: missing the audience check, not validating the issuer, or using a library that silently ignores token expiration. Always test your JWT implementation thoroughly, including edge cases like tokens with extra whitespace, tokens that are tampered with, and tokens using different algorithms.

Finally, be aware of the 'none' algorithm attack. Some JWT libraries accept tokens with alg: 'none' unless you explicitly disable it. An attacker can craft a token with any payload and set the algorithm to none. The library will treat it as unsigned and trust it. Always configure your JWT library to reject unsigned tokens and to only accept a whitelist of algorithms you intend to use. In professional practice, it is also wise to pin the expected algorithm rather than reading it from the header, or at least validate that the algorithm in the header matches what you expect.

## Memory tip

Think of a JWT as a laminated ID badge: the header is the badge type, the payload is your name and photo, and the signature is the holographic seal that prevents forgery.

## FAQ

**Can a JWT be decrypted?**

Not by default. A JWT is only base64url encoded and signed, not encrypted. Anyone can decode the payload and read its contents. If you need to hide the payload, you must use JWE (JSON Web Encryption) which is an extension of the JWT standard.

**What is the difference between JWT and JWS?**

JWT is the overall standard for JSON-based tokens. JWS (JSON Web Signature) is one specific type of JWT that uses a digital signature to ensure integrity. When people refer to JWT, they usually mean a JWS. There is also JWE (JSON Web Encryption) which provides confidentiality.

**Is JWT secure?**

JWTs are secure when used correctly. The signature prevents tampering, and if you use HTTPS, the token is protected in transit. However, the payload is not encrypted, so sensitive data should not be placed inside a JWT. Also, the security depends on proper validation of the signature, expiration, and other claims.

**How do I revoke a JWT before it expires?**

Because JWTs are stateless, you cannot directly revoke a token. The common approach is to maintain a blacklist of revoked token IDs (jti claim) on the server side and check the list on each request. Alternatively, use a short token lifetime combined with refresh tokens that can be revoked individually.

**What is the maximum size of a JWT?**

There is no official maximum size, but since the token is usually sent in an HTTP header, most servers and proxies impose a limit on header size, typically around 8KB to 16KB. For practical purposes, keep the payload as small as possible to avoid hitting these limits and to reduce network overhead.

**Can I use JWT without HTTPS?**

Technically yes, but it is extremely risky. Without HTTPS, the token can be intercepted in transit. An attacker could steal the token and use it to impersonate the user. HTTPS is a mandatory security requirement for any production system using JWTs.

## Summary

JWT stands for JSON Web Token, a compact, URL-safe token that encodes claims as a JSON object. It consists of three parts: a header that specifies the algorithm, a payload that contains the data, and a signature that ensures the token has not been altered. The key advantage of JWT is its stateless nature. The server does not need to store session data; all the necessary information is inside the token itself. This makes JWTs ideal for scaling applications and for use in microservices architectures.

In IT certification exams, JWT appears in topics ranging from authentication and authorization to identity federation and API security. You should know the structure of a JWT, common security pitfalls like storing sensitive data in the payload or accepting the 'none' algorithm, and best practices such as short token lifetimes and proper validation. Understanding the difference between JWT and other token formats, like SAML and opaque tokens, is also important.

For the exam, remember that JWT is not encrypted by default. Security comes from the signature, not from hiding the data. Always validate the expiration time and use HTTPS. A common exam trap is to think that JWT is encrypted because of the base64 encoding. The correct understanding is that base64 is encoding, not encryption. By keeping these principles in mind, you will be well prepared for any JWT-related questions on your IT certification exam.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/jwt
