JWT — JSON Web Token . What is it?

Soumyajit Dutta
Jan 3, 2018 · 7 min read
JWT Topology

Nowadays everyone is making one or the other APIs for making their Backend Systems or codes to interact with the Frontend and thus there is an increase need of security and also maintainability for the codes and also the way we write it.

REST APIs or stateless APIs as we call them is majorly used, because they don’t rely on the current state of the sender nor the device its being accessed from. REST APIs are also mostly used when there is a constant need to diversify the same code for working in various devices or platforms

So suppose you made an API which works on Request types like GET,POST,PUT and etc etc and make it public, and also it is a Rest API. What if I create a script in any language I prefer and call it from high computing power like Cloud Instances or whatever. Yes you will think , I cannot access your data because the input data I pass won’t be correct. But I don’t care, as long as I am using your compute power and using the API to overload your system, my work is done. Your API Server if not protected would be down in any moment by just hitting it, and moreover what if I hit your API with correct parameters but you don’t know who I am or where am from. Maybe I am not authorised to see that data, but someone who is shared me his parameters or headers and now I can access that data without you catching him again or stopping me at all.


JWT — JSON Web Token

What is JSON Web Token?

JSON Web Token is a open standard (RFC 7519) that defines a compact and self constrained way for securely transmitting and verifying data. All data sent through JWT is digitally signed thus can be verified and also trusted. All JWT Tokens are signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

Let’s state the types of JWT we know:-

  1. Compact:- JWT tokens and datas can be compact and also streamlined to small size. Due to their small size and also better delivery pipeline, due to less overhead they can be sent through HTTP Parameters or Methods like POST,GET,PUT requests etc. They are generally done when small access token is needed to be sent to the Client after authorisation.
  2. Self Contained:- Self Contained way or method has the total payload inside the JWT Request, generally POST method is used for the same. All the content is send at once. This is generally done when the response data is too large and accessing again or requesting again would increase the access time or resource utilisation.

Where and Why should we use JWT Tokens ?

  1. Authentication:- The most common and also the main reason for which you started Googling about JWT is 99% chance that you needed some authorisation or verification of who and when is your API getting called. This is why JWT is actually there at first. Using JWT you can have a single login system, and that is the trending way of using API Nowadays for the less overhead. Each Request to Login Server generates a token, which can have total or custom permissions for Routes, Directories,services and other resources.
  2. Information Transfer:- Now this is a feature which can be modified into JWT. As you can think of JWT is a signed or encrypted piece of information.Tokens are a good way of securely transmitting information between parties. Because the tokens are signed , we can be sure that the person who is receiving a message or the token is surely that person or not.Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.

Structure of JWT:-

JSON Web Tokens mainly look like

xxxxx.yyyyy.zzzzzheader.payload.signatureeyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9           // header
.eyJrZXkiOiJ2YWwiLCJpYXQiOjE0MjI2MDU0NDV9 // payload
.eUiabuiKv-8PYk2AkGY4Fb5KMZeorYBLw261JPQD5lM // signature

So breaking them into parts it would look and mean something like:-

  1. Header:- Header part as the name suggests is the starting point of data storage or work for JWT. It mainly consists of 2 Data, i.e, the type of Token which in here is JWT and the other is the Hashing Algorithm to be used in the token henceforth like HMAC SHA256 or RSA.

Example:-

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

Then the upper part of the Data is Base 64 Encoded for making it the first part of the total String or Token as preferred.

2. Payload:- Now we all have data that needs to be added to the JWT Token for some purpose. Like we are authenticating an user and we need to add a Secret User Token that is used as an Primary key to get other details from a DB. So we can add this data into the payload of the JWT Token. These type of data are generally called Claims. There are generally three types of Claims Registered Claims, Private Claims, Public Claims. Claim names are always only 3 Characters long just like Token Type “JWT”.

Registered Claims are in the IANA “JSON Web Token Claims” registry. They have specific name and use. Each of those are kind of reserved for a specific purpose. These are a set of predefined claims which are not mandatory but recommended. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience) and more.

Public Claims can be defined by will of the person using it for their own code, but due to huge number of possibilities and collisions it is recommended to be defined in the IANA JSON Web Token Registry or be a Public Name, a value that contains a Collision-Resistant Name. In every phase the definer or the Programmer must be aware and also in control of the namespace they are using defining that Claim.

Private Claims are just like a normal variables. They are mutually agreed claim names and need not depend on any rules or Registry Guidelines. These Claim names are those which are not registered under IANA for both Registered and Public Claim Names. Only the both end users are responsible for knowing the meaning and the tag they use for transfer of Data.

Example of Claims:-

  • iss: issuer of the token
  • exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds.
  • iat: The time the JWT was issued. Can be used to determine the age of the JWT
  • nbf: “not before” is a future time when the token will become active.
  • jti: unique identifier for the JWT. Used to prevent the JWT from being re-used or replayed.
  • sub: subject of the token (rarely used)
  • aud: audience of the token (also rarely used)

Example Payload:-

{
"sub": "This is a test Subject",
"iss": "Soumyajit Dutta",
"designation": "Blogger",
"admin": true,
"sub" : "Medium Blog"
}

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

3. Signature:- The Signature is the third part of the JWT Body. Here we make the data signed.

A Shed of light on the Truth

Many people confuse JWT as a data hiding or data encryption. And many of people have asked me that does it make the payload unreadable and can we add sensitive data into it. My answer is no. Even though it might look like the data is getting encrypted, but in actual its not. It is just getting signed. If we take the middle part of string and base64 decode it , we will get a JWT Payload in normal form without the secret. But when we would try to decode the whole JWT it would say signature not verified. The main use of JWT is not to encrypt and send data but generally to be used in replacement as a Authentication mechanism with respect to Session Variables. Here the server knows you have logged in once and till the expiration time the JWT token will be decoded successfully and you can use the resources as required.

So coming back to signature, it is the most easiest yet important part of the total JWT Token, the Header and Payload along with the Secret Token is encoded into a Hash and sent back.

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 that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.


All Together :-

The three parts of the JWT Token are appended with dots in between and is in normal ASCII Text so that it can be sent on normal HTTP and HTTPS Requests like GET and POST.

JWT TOKEN

This is how a JWT Token looks like after encoding it. The red part represents the header of the JWT Token. The purple part represents the Payload where all the data is there. Now the last part in blue represents the signature which contains the Base64Url encoded version of the above two parts with a secret text or word.

On the next story I would write a more detailed way on how JWT actually work and also code snippets in NodeJS and Python to help you ace through it.

Soumyajit Dutta

Written by

I am a professional Backend and DevOps Developer I mainly work on NodeJS and Python based Backend. On Cloud I have my forte on AWS and Azure.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade