What the heck is JWT anyway?

In this article we will learn the fundamentals of a JWT token is and how we can benefit from it for authenticating communications between two parties, all of this using vanilla NodeJS and javascript.

JWT is an abbreviation for JSON Web Token, which is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS). ~ IETF

Urggh! What?

Simply put, JWT token is a string we pass in the header or url while making a network request to pass data safely and make sure it hasn't been tampered with.

The second part of the token is the payload, which contains the claims. Claims are predefined keys and their values. There are three types of claims: registered, public, and private claims.

Registered claims: These are a set of predefined keys which are not mandatory but recommended. Some of them are iss (issuer), exp (expiration time) etc.

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 are the custom key value pairs created to share information between parties that agree on using them and are neither registered or public claims.

{"exp":"2019-02-14","message":"roses are red"}

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

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. Too good for us that NodeJS comes with the immensely powerful Crypto library out of the box which we will use in our example.

You can use JWT token for various types of authentications, even for logged in users. For example when a user logs in to your website with their credentials, the api response might return a JWT token as a part of the response. After logging in, on subsequent calls to the API, the client (browser) can send the JWT token to the server and on authenticating the token, the API can return results to make sure it's a legit request.

You can definitely store a JWT token in the client in cookies, local / session storage based on your need. Just make sure to not generate the JWT token in the client as the secret will be visible on inspecting source.

Ideally you should! The payload part can contain a claim called "exp" whose value should be a timestamp when the token expires. That way the same token cannot be highjacked by someone else and used to make API calls impersonating the actual user.