JWT (JSON web tokens), JWE (JSON Web Encryption)WHY..? WHAT..? WHEN..?

Shanaka Sandanayaka
6 min readJan 1, 2021

In the recent past, Many web applications are trend using JWT over the sessions for authentication. Even though both of these approaches have many benefits as well as drawbacks, JWT’s are much popular due to certain factors.

Why we need JWT…?

As we all know HTTP is a stateless protocol. But when we develop modern applications, It’s required to maintain a state (Some sort of identity).

For example, Assume you are using a travel website. In that case, In order to make a booking First, you have to provide a username, password, and authenticate yourself. Once authenticated, It will give you a key. Each and every request afterward, Need to send with that key. Then the server knows it is from you. If not for each and every request you have to provide your username and password to perform actions. This is a very basic example of how stateless protocols such as HTTP maintain the sessions.

In the above example, We will give a key. In the HTTP, There are 2 types of keys (Or a token) mainly.

  1. Reference token
  2. JWT tokens

Reference token —

In this case, Once the user is authenticated, It will maintain a session store on the server-side and a reference token related to that session will be provided to the user. Once the user makes another call with that token on the server-side, It will validate that token with the session store and identify necessary information from that session.

Can you see a downside in this approach? Yes, Assume the demand for your service is too high. In that case, It needs to maintain a very large session store and need to horizontally scale. And also this is a single point of failure.

What if we could create a create a custom token with all the metadata included and provide to the user to use as that token for rest of the calls. Well this reduce the burden on maintaining session store on server side also remove the concern of single point of failure due to session store. Finally reduces the complexity of scaling as well.

So then comes the JWT (JSON Web Token). Also known as the self contained access tokens.

What is JWT..?

According to Wikipedia, JWT (JSON Web Token) is an Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key.

In simple terms, This is a token with 3 parts and the main part call Payload is a JSON body that represents a set of key-value pairs that are call claims. And other 2 parts call header and signature used to identify and validate the authenticity of the token. Finally, all of them are Base64 encoded.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

This is a sample of a JWT token. As you can see it has 3 parts separated by “.”

  • 1st Part of the JWT is call header.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

{
“alg”: “HS256”,
“typ”: “JWT”
}

  • 2nd Part calls body

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

{
“sub”: “1234567890”,
“name”: “John Doe”,
“iat”: 1516239022
}

  • 3rd part calls as Signature

SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Each of these parts having a separate use cases.

Header

This topically contains the information regarding the representation of JWT such as type, algorithm used to sign the token and the it can have multiple claims depends on the use case. Refer to the https://tools.ietf.org/html/rfc7519#section-5 for more information.

Payload

This is the place where all the claims (peaces of information) contains. There are mainly 3 type of claims.

  • Registered Claims : These claims are reserved by the JWT specification and usage of these claims not mandatory but recommended usage is based according to the JWT spec.
  • Public Claims : These claim names are defined in JWT specification, 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 claims are custom set of claims agreed by the parties which is issue and use JWT.

Signature

As explained previously, JWT’s are simply a JSON structure base64 encoded. Anyone can decode the JWT and modify the content of the body and could use that to perform unauthenticated transactions. There should be a method to validate the token is issued by the valid party. The intention of the signature is to ensure that authenticity.

Signature is calculated using the header and the payload section of the JWT. Due to this, If the payload or the header is altered then the signature becomes invalid. Usually, the JWT issuing party uses it’s private key to generate the signature. And the shared public key or the JWKS response to validate the signature.

When to use JWT…?

There are mainly two occasions where we needed to use JWT tokens.

  • Authentication & Authorization
  • Exchange the information

Authentication & Authorization

Speceally with the SPA’s and the Mobile applications, JWTs can be used as an authentication mechanism that does not require a database. Once the user is successfully logged in, IDP will issue a JWT token and the application could use that JWT as as the Authorization token for the API calls afterwards.

Since the JWT token dose contains all the meta-information needed such as scopes and roles inside the token itself. API’s can decide whether the requested resources are authenticated to serve according to that information. And also the signature could use to check the issuer as well as the token is not altered by a middle man.

Exchange the information

Since the JWT’s are singed as well as it could encrypt the if needed, This is a secure medium of sharing the information. JWT issuers could be configured to share the necessary claims accordingly. And both client and the API’s are benefited from those claims depends on the usage.

Anyhow, JWT’s are not suitable to use if,

  • There is no secure way to store the JWT’s in client side.
  • When HTTPS is not using.
  • When there are network level consequences are there such as the header size limitation…etc.

What is JWE (JSON Web Encryption)…?

As we explained about the JWT, the payloads are just base64 encoded. Anyone can decode the token and see the content of the token very simply. jwt.io is the most populer website doing that.

But if the JWT is containing very sensitive information and if there are any complients needs to be ensure those are not exposed outside, Then we can use the JWE’s. This is representing encrypted content using JSON data structures. JWE specification mainly has 2 serialization forms to represent the encrypted payload.

  1. JWE Compact Serialization
  2. JWE JSON Serialization

The more common one, JWE Compact Serialization. It has five key components, each separated by a period (.).

eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.
OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGe
ipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDb
Sv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaV
mqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je8
1860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi
6UklfCpIMfIjf7iGdXKHzg.
48V1_ALb6US04U3b.
5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6ji
SdiwkIr3ajwQzaBtQD_A.
XFBoMYUZodetZdvTiFvSkQ

We will further discuss the JWE’s in a separate blog :).

Hope this blog will provide a small briefing about the JWT tokens. Thank you.

Happy Coding :)

--

--