JWT Token Auth | JSON Web Tokens in Node.JS

When you create a REST service or any backend server for a website or an app, there is one talk about this new trending method for authenticating the user who is requesting your servers for data.

  Previously there were only a few ways to know where is the request coming from. That could be storing cookies, sessions in browsers, and using them to identify the user. So this method evolved, the trick is to create a string that has info of the user and data about the user.

  So JWT has payload, header, and signature which has info of the user and other important data. Why JSON you ask? because JSON is less verbose than XML and when encoded the size is small to easily use in HTTP transmissions.

The authorization token is passed as:
 Authorization: Bearer <token>


How it works?

  1. User signs in with username and password. 
  2. The server creates a JWT using one of the algorithms (HMAC, RSA, or ECDSA).
  3. Then this token is sent to the user and every interaction excepts a token in the header              
  4. The user can then store the token, and send it with every request
  5. If the user fails to do this, he/she has to reauthenticate with the server to obtain the token.

Diagram

Now some code:

I have created an express app in Node.JS. And some endpoints will listen:

/login: simple login with username and password, here we will create the JWT. /getData: get a request to get some data from the server.

1. Create a login endpoint, accept username and password, and send back the token.

2. Create a verification function, keep it separate so that you can play with it later



3. Another endpoint that checks the token, now it is fairly simple just add our function as middleware



Popular posts from this blog

Audio de-noising using Python (Wavelets)

Using FFMPEG to trim your videos

Converting HTML5 Game for Android | 2 Methods