All about Authentication  (3/3) :  JSON Web Tokens

All about Authentication (3/3) : JSON Web Tokens

Hello and welcome to the final chapter of my All about Authentication blog series. We discussed Authentication in brief and learned about Passport.js & OAuth in previous chapters. If you haven't read, please check out from the below link

All about Authentication (1/3) : The Fundamentals

All about Authentication (2/3) : Passport.js & OAuth

In this short article, we'll be learning a different approach to authenticate users. In all previous methods, we have hooked to session-based authentication. That means our primary method of persistent log-in was sessions stored on the server-side. However, there is another method to authenticate users i.e JWT (JSON Web Tokens).

Let's understand what is JWT and then see how to use it.

What is 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.

JSON Web Token is a protocol to transfer information between two parties in a compact and secured way. It's secure because it is digitally signed ( encrypted ) before sending away. This ensures that the receiving party doesn't get a tampered token.

When can it be used ?

It can be used in these two scenarios :

  • 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 permitted with that token. It can be implemented across different domains easily.

  • 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.

Structure of a JWT

A JSON Web Token consists of 3 strings separated by a dot (.). These strings represent specific entities orderly. They are

  1. Header
  2. Payload
  3. Signature

It looks like this

JWT Structure.png

Let's understand different parts and their roles.

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

For example

{
    "alg": "HS256",  // algorithm used
    "typ": "JWT"     // type of token
}

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

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 claims.

  • Registered : These are a set of predefined claims which 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.

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

For example

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

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

Signature

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.

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)

Putting it all together

The output is three Base64URL 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.

The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret.

JWT sign process.png

How to use it in web authentication ?

auth with jwt.gif

Using JWT in web auth is a simple approach.

  • Client side : We need to store a JSON Web Token on the client side and with every request it is sent to the server. It can be either stored in cookie or in local storage. Both the options are debatable have their own pro's and con's. Usually information like user id as a payload is kept in JWT.

  • Server side : Every incoming request should contain a JWT in either cookie or Authorization header. This token is then verified with the secret key, looked for tampered token. If everything is okay then, decoding the token gives us the identity of the user. Then this request is passed to the next middleware which handles accordingly and give a response.

Implementation differs for different platforms. There is a module/SDK available for different environments. I encourage you to jump on their official documentation and learn how to implement it.

JWT Official Documentation : - jwt.io

That's all for this article. I hope you find it useful. If there's any improvement/ suggestions, I will be happy to know and apply.

Thank you. Keep learning, keep hustling🕵️‍♀️.