JSON Web Token (JWT) Basics

Updated on March 25, 2024

In this Lab, you will:

  • Learn What a JSON Web Token(JWT) is.
  • Understand the structure of JWT.
  • Learn how to decode a base64 encoded string
  • Verify the signature of a JWT.
This lab is built based on Introduction to JSON Web Tokens.

What Is JSON Web Token (JWT)?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Although JWTs can be encrypted to provide confidentiality between parties, we will focus on signed tokens. Signed tokens can verify the claims' integrity, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.

When Should You Use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

  • Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are scoped to that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.

Why Use JSON Web Tokens?

Let's talk about the benefits of JSON Web Tokens (JWT) when compared to Simple Web Tokens (SWT) and Security Assertion Markup Language Tokens (SAML).

As JSON is less verbose than XML, its size is also smaller when it is encoded, making JWT more compact than SAML. This makes JWT a good choice for HTML and HTTP environments.

Security-wise, SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can use a public/private key pair in the form of an X.509 certificate for signing. Signing XML with XML Digital Signature without introducing obscure security holes is very difficult compared to the simplicity of signing JSON.

JSON parsers are common in most programming languages because they map directly to objects. Conversely, XML doesn't have a natural document-to-object mapping. This makes it easier to work with JWT than SAML assertions.

Regarding usage, JWT is used at the Internet scale. This highlights the ease of client-side processing of the JSON Web token on multiple platforms, especially mobile.

JWT vs SAML

Comparison of the length of an encoded JWT and an encoded SAML

If you want to learn more about JSON Web Tokens and even start using them to perform authentication in your applications, browse to the JSON Web Token landing page at Auth0.

JSON Web Token Structure

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following:

xxxxx.yyyyy.zzzzz

Let's break down the different parts.

Header

The header typically consists of two parts: the token type, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

For example:

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

Then, this JSON is Base64Url encoded to form the first part of the JWT.

If we remove new lines and spaces and then encode the example, the output would be the following:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private.

  • Registered claims: These are a set of predefined claims that are not mandatory but recommended to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.
Notice that the claim names are only three characters long as JWT is meant to be compact.
  • Public claims: These can be defined at will by those using JWTs. But to avoid collisions, they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision-resistant namespace.

  • Private claims: These custom claims allow the sharing of information between parties that agree to use them and are neither registered nor public claims.

An example payload could be:

{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}

The payload is then Base64Url encoded to form the second part of the JSON Web Token.

Encoding the payload, like we did for the header, the output would be as follows:

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
Do note that for signed tokens, this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.

Signature

To create the signature part, you must take the encoded header, the encoded payload, and a secret and use the algorithm specified in the header to sign them.

For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

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

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is. The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret:

jwt token example

The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments while being more compact when compared to XML-based standards such as SAML.

In the next sections, you will play with JWT and put these concepts into practice. You can use jwt.io Debugger to decode, verify, and generate JWTs.

jwt.io debugger

Decoding Pieces

Now that you have learned the basics of how a JSON Web Token (JWT) is structured and how it works let’s put all that knowledge into practice by playing a puzzle:

A JWT has been broken into multiple pieces. Your goal is to put those pieces together correctly to form a valid JWT with a verified signature. You’ll practice how to form a valid JWT header and payload. You’ll practice cracking the secret to verify a JWT signature.

Let’s get started!

Sample JWT pieces
cCI6IkpXVCJ9
eyJhbGciOiJI
vbd6js8G66H3
Me69RqSE-0w3
eyJuYW1lIjoi
LCJpYXQiOjE2
PtEH73_fTnj4
bevBfNE
UzI1NiIsInR5
RGV2RGF5MjMi
ODQyNDU2MDB9

Let's choose the first piece, cCI6IkpXVCJ9, and use the base64 command on macOS & Linux to decode it:

MACOS
LINUX
echo 'cCI6IkpXVCJ9' | base64 --decode

On Windows, you can use the certutil command to decode a file.

Let's create a file named sample-JWT.txt, then put the piece inside.

WINDOWS
certutil -f -decode sample-JWT.txt output.txt

The output should be the following:

p":"JWT"}
If you use Zsh, you may observe the percent sign (%) at the end of the output. The shell tells you the command did not end in a new line.

Now, you can decode other pieces and build a header and a payload by following the structure explained previously.

You can also create a simple program with a language of choice to automate decoding.

Some decoded outputs would include garbaged characters or completely be empty. Those are part of a signature, so do not worry.

Let's move on to the next section to verify the signature of a JWT.

Verify the Signature of a JWT

In this section, we will cover how to verify the signature of a JWT using the jwt.io debugger.

Suppose you managed to put the pieces together to get the following JWT:

Sample JWT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiRGV2RGF5MjMiLCJpYXQiOjE2ODQyNDU2MDB9.PtEH73_fTnj4vbd6js8G66H3Me69RqSE-0w3bevBfNE

If you open the jwt.io on your browser and paste the JWT to the Encoded section, you will see Invalid Signature.

invalid signature

This is because the default secret (your-256-bit-secret in this case) on the page does not match the actual secret.

The secret of this JWT is “useauth0byoktatobuildyourcustomidentitypipeline” (no space, no period, all small letters).

If you enter a correct secret, you will see Signature Verified sign on the page.

valid signature

Congratulations! You verified the signature for this Lab by finding a valid secret!

BE AWARE: If you enter a wrong secret, you will still see Signature Verified on the page because jwt.io changes your signature to match the wrong secret. Once you enter a secret, we recommend you paste the original JWT to ensure the site validates the correct JWT.

Appendix: How do JSON Web Tokens work?

In authentication, a JSON Web Token will be returned when the user successfully logs in using their credentials. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.

You also should not store sensitive session data in browser storage due to lack of security.

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

Authorization: Bearer <token>

This can be, in certain cases, a stateless authorization mechanism. The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources. If the JWT contains the necessary data, the need to query the database for certain operations may be reduced, though this may not always be the case.

Note that if you send JWT tokens through HTTP headers, you should try to prevent them from getting too big. Some servers don't accept more than 8 KB in headers. If you are trying to embed too much information in a JWT token, like by including all the user's permissions, you may need an alternative solution, like Auth0 Fine-Grained Authorization.

If the token is sent in the Authorization header, Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies.

The following diagram shows how a JWT is obtained and used to access APIs or resources:

diagram with jwt
  1. The application or client requests authorization to the authorization server. This is performed through one of the different authorization flows. For example, a typical OpenID Connect compliant web application will go through the /oauth/authorize endpoint using the authorization code flow.
  2. When the authorization is granted, the authorization server returns an access token to the application.
  3. The application uses the access token to access a protected resource (like an API).

Do note that with signed tokens, all the information contained within the token is exposed to users or other parties, even though they cannot change it. This means you should not put secret information within the token.

Recap

In this Lab, you learned:

  • Learn What a JSON Web Token(JWT) is.
  • Learn the structure of JWT.
  • Learn how to verify signature on jwt.io

If you want to learn more about JWT, you can download a JWT Handbook.