Simple token authentication with nodejs and JWT ( JSON Web Token)

photo-1515879218367-8466d910aaa4-1

Who am I?

I don’t even know myself

My name is Yashlin and I am a software engineer currently specialising in web application development. I’ve worked with lots of different technologies ranging from the bleeding edge to legacy and I would like to add some simple but powerful tools to your arsenal.

Why?

Who knows boet , suggest me something. ivermectina de quanox precio

Authorization 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. Single sign-on is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

Pre-requisites:

Stuff you need to know before we do the stuff 

  • Foundational understanding of javascript and javascript standards.
  • Foundational understanding of nodejs and the node package manager (NPM)
  • Basic understanding of software concepts like middleware and restful api’s and the part they play in web application engineering.

Let’s Begin:

Finally , admin is boring.

  • You will need nodejs installed on your developer machine , at the time of writing , the current version I have installed is: v12.13.0
  • You can download postman here , it’s a great tool that lets you test your API and Integrations , the free package is more than adequate for our needs
  • As always the sufficient permissions needed to execute the various commands and scripts successfully.

Disclaimer:

Please don’t sue me if your house catches on fire 

This tutorial is not an introduction to nodejs or any of the underlying principles and practices , please skip this unless you are familiar with nodejs and javascript as well as creating routing and api’s using this platform.

Creating your package.json and index.js file:

Firstly lets create a project directory , name it something meaningful to you and then using your terminal of choice you can path into the directory and run npm init , this will create a package.json which houses and helps us manages the dependencies needed for this nodejs application.

When following the npm init questionnaire give your project a name , stick with the default version and then a short description , you can press enter for the other questions unless you have experience filling them out. Your project directory will now have just a package.json file 

terminal image

Next we need to start setting up our index.js file in order to house all of our middleware logic , firstly we create a javascript file called index.js in our directory , then we require the non-native packages that we need in order to make use of their methods and resources.

This will house all the logic , best practice dictates we have some separation of logic but for the purposes of quickly creating a sandbox for you to test the logic and concepts you will learn in this tutorial , we are going to combine everything.

Creating the index.js is very simple , open up your favourite code editor , select create a new file or similar , name that file index and then make it a javascript file (which is denoted by .js) .

Installing the dependencies:

Thankfully our concept is quite low-weight so we aren’t going to be navigating dependency hell over here , we will only require three packages which can be easily installed by running the following scripts.

npm i express

npm i jsonwebtoken

npm install body-parser 

Express: lightweight server framework which helps us scaffold our middleware into best practice patterns

Jsonwebtoken: the packages responsible for encrypting and decrypting our data payloads into tokens for consumption by both the server and the calling application.

Body-parser: Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Setting up your routes and testing them

Now that we have the packages we need lets get started with a base route and our server configurations so that we can check everything is working as expected.

The code is pretty simple here , we are going to set up a GET route so whenever anyone tries to access our “/api” route they get greeted with a message.

Next we need the server to actually listen  to these incoming requests and respond with the appropriate resources.

The app.listen code will ensure the app spins up and listens to incoming requests on a certain domain and port , in this instance the domain will be localhost and we have hard coded the port to be 5000.

We can check that our code is correct by using the following command , node index.js , this  will execute our code and if everything works fine we should see the following in the command line.

Making a simple GET request to localhost:5000/api should then yield the following:

So far we have set up our server to listen to incoming requests and defined a base route as well as checked that our requests are being received and responded to appropriately , let’s continue…

Creating and testing your login route (getting your first token)

For the sake of a “bite-sized” tutorial we are going to mock a typical user login request , what we want to achieve is the following:

  • Receive the user payload
  • Using the JWT package we want to encrypt this user payload into a token and pass it back to the calling application so that we can authenticate requests from that user 
  • Everytime an application tries to request resources from our server , it will now require a token which will be verified and only then can a user access protected routes

let’s break down this code 

We have created a mock user here which resembles a typical login request , we then use a method of the JWT package called sign , sign does the following :

It accepts the user payload and secret key as well as a callback function , we use this call back to sign the payload into a token and then we return this token

The sign method has many different options that it can accept and this all extends its functionality. If you want to read more about this please check out the link below:

https://www.npmjs.com/package/jsonwebtoken

Testing your login route and getting a token

We can do this by firing off a simple postman POST request to our server and route address which will contain our payload information , the route logic will parse the body of our request and extract the information we need in order to create our token and then pass us a token which we can cache on the calling application for use in subsequent requests to our protected routes.

Creating a function to extract the token from the headers

The best practice for passing tokens is through the authorisation header and this has become an industry standard.

You can read about the “Bearer” authentication scheme we are going to use here : https://swagger.io/docs/specification/authentication/bearer-authentication/

We are going to create a simple function called verifyToken which will check that each request at least contains a valid token ,

Let’s break down the code:

First we assign the value of the authorization header to a constant , we then split that constant into the two different values ‘Bearer’ and the token value ,since split will return an array of strings ,  the token will be at the second index in the bearer array.

Granting access to protected routes using token authentication

We now need to create another route which is going to be our ‘protected’ route. The premise is simple , we have an api called posts which will accept our token and then once verified it will return a message with the token deconstructed into the same payload we passed in the auth request.

Let’s break down the code

We now use a different method of the JWT packaged which is verify , verify accepts the same secret key we used to sign the token in order to deconstruct it. It also accepts a callback which is used to perform logic in the event of successful verification and unsuccessful verification.

Once again we can test to see if our logic has worked by firing off a simple postman POST request to that route and include the token in the authorization header (Don’t forget to include the keyword “Bearer” one space before your token). ivermectin/pyrantel pamoate

Conclusion

In conclusion , token authentication is a great way to add critical security features to your applications. Simple , lightweight and cross-platform means it scales really well and if implemented correctly can add a lot of flexibility. I hope this tutorial helps you understand the tools and concepts needed to successfully implement this in your projects!

Glossary:

JWT- 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. This information can be verified and trusted because it is digitally signed.

Restful API’s – A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.

Integration testing – is a level of software testing where individual units are combined and tested as a group. The purpose of this level of testing is to expose faults in the interaction between integrated unit.

Bearer authentication (also called token authentication) – is an HTTP authentication scheme that involves security tokens called bearer tokens. The name “Bearer authentication” can be understood as “give access to the bearer of this token.” The bearer token is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the Authorization header when making requests to protected resources:

Useful resources:

https://www.npmjs.com/package/jsonwebtoken

https://swagger.io/docs/specification/authentication/bearer-authentication/

https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e

About the Author