JSON Web Token(JWT)

Akash Shyam - Feb 28 '21 - - Dev Community

When building rest APIs with express, authentication is usually done using JSON web tokens(JWTs) or sessions. In this post, we are going to look at JSON web tokens.

What are JWTs?

JWTs are a secure way of transporting data. Basically, our data is encrypted with an algorithm HMAC using a string we specify(called secret).

JSON Web Token is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

Creating a JWT

JWTs are created using the jsonwebtoken package.

npm i jsonwebtoken
Enter fullscreen mode Exit fullscreen mode

We use the sign method to create tokens

const jwt = require('jsonwebtoken');

jwt.sign(PAYLOAD, SECRET, OPTIONS_OBJECT)
Enter fullscreen mode Exit fullscreen mode

The payload is the data we want to encrypt. The secret is the string that is used to encrypt the data. The secret should always be a secret(pretty obvious.... I know). If a hacker gets hold of the secret he can easily decode the secret information that you send in the JWT. We should always store the secret in an environment variable. The secret should be around 32 characters to make it really secure .We can specify an options object too. I normally add the expiring time(time until JWT is valid) in the options object. Now our example looks somewhat like this -

jwt.sign({ example: 'JWT' }, process.env.JWT_SECRET, OPTIONS_OBJECT)
// JWT_SECRET is "jjksj238429810sjk"
Enter fullscreen mode Exit fullscreen mode

2 ways of decoding a JWT

JWTs are decoded by the jwt.decode() or jwt.verify() methods.

jwt.decode() only decodes the token but does not check if the token was malformed. jwt.verify() decodes the token and also checks if it was malformed.

How JWTs are used?

JWTs are used for user authentication in a website. The client makes a call to the server. If the client wants to signup then the server creates a new user with the data and gives a token. If the client wants to login, then the server compares the info of the user provided with the client to the information that is encoded in the token. This token is then used to access various protected routes.

Advantages of JWTs

A REST API is supposed to be stateless. In our example, stateless means that the REST API should not know whether the user is logged in or not. JWTs enable our API to do just that. By using JWTs we let the client handle the state and we can also follow the convections of a REST API.

Before JWTs

Before JWTs, cookies were used on the client side and sessions were used on the server. The process began by the user submitting a login form to the server. The server validates it and creates a session in the database and responds with an ID of the session.

The browser puts this ID in a cookie. Cookies are key values pairs that can be stored in the browser and are sent to the server on each subsequent request. The server can then reply with the appropriate response.

There are some drawbacks to this approach. CSRF or cross site request forgery where the attacker points the user to a website they are logged in to, to perform actions they did not intended to. For example reseting password, submitting payment etc.

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated

Another drawback is that the sessions have to be stored in a database or in some other place on the server. Because most of the cloud applications are scaled horizontally(adding extra virtual machines instead of increasing the power of a single virtual machine). This can be a gigantic bottleneck in production sites.

The main difference between sessions and tokens are that the authentication state is managed on the server when we use sessions and on the client when we use tokens.

. . . . . . . . . . . . . . . . . . . . . . .