JWT Authentication using NodeJS

Moshe Binieli
6 min readSep 20, 2018

--

Simple JWT Authentication explanation
Article about C# implementation

After seeing some people struggle with authentications systems, I’ve decided to create JWT Authentication with NodeJS.

Clients security with JWT

You might be asking yourself what is JWT?

JWT is JSON Web Token.
It’s a token that only the server can generate, and can contain a payload of data.
A JWT payload can contain things like UserID or Email so that when the client sends you a JWT, you can be sure that it is issued by you.

There is plenty of information out there about JWT, we’re here to implement JWT and not explain what it is, let’s start the implementation.

Something important before we start this guide, you must be familiar with the following things:

  • NodeJS
  • NPM
  • JavaScript

Before we start this guide, I suggest everyone to visit the actual jsonwebtoken npm documentation, it’s well written, good examples and it is just amazing — Click here.

Pick your favorite IDE, I’m taking Visual Studio Code since it’s really cool :)

Open new folder and navigate with your command line to this folder and then type “npm init”, and then just press “Enter” on every question it asks you.

Visualization of “npm init” process

It’s time to install the package that will do the work for us, type “npm install jsonwebtoken --save” in your command line.

Visualization of installing the required package

Let’s open our project with our favorite IDE and start creating the relevant files for this guide, we’ll create two JS files which will be called ‘Main.js’ and ‘JWTService.js’.

  • Main.js file - This file will be responsible to run all the program.
  • JWTService.js file - This file will contain all the logic for JWT Implementation.
Visualization how the project should look like

Shall we start writing the code? :)

We’ll implement JWTService.js as separate file from the project for reusability and code separation.

Let’s write the basic code for this file, we import the package ‘jsonwebtoken’ and create new function called JWTService and we will export it.

This function will behave like a class, we will write this implementation in ES5, we will inject the secret key inside this “class”, we want to inject the secret key from outside the class and not from inside, the secret key should be in server configurations.
We will create object “methods” that will define all this “class” methods and we will return it.

For validation purposes we will define two methods that will perform validations on our object and token (string).

  • isObjectNullOrUndefined : boolean - This method validates whether given object is null or undefined.
  • isStringNullOrEmpty : boolean - This method validates whether given string is null or undefined or empty.
Creating two first methods for validation purposes

Time to start the actual implementation of JWT Authentication, we’ll start with the method generateToken, this method will receive object that will contain the following keys:

  • data - This object will contain all the data we want to store in the payload, for example: name, email and etc.
  • expireDate - This object will store how much time the token will be valid for, for example: 1 hour, 7 days, or 1 second, it’s your choice.

When we’re going to generate the token by the given object, we will check that the object is not null or undefined, then we will use method from ‘jsonwebtoken’ which is called ‘sign’, this method receives 3 parameters, the payload, the secret key and options, therefore our method will look like this:

generateToken method implementation

Important note: The default encryption algorithm is HMAC SHA256, this can easily be changed, I encourage you as developer to explore ‘jsonwebtoken’ documentation and understand how to use another encryption algorithm.

The second method we will implement will be called ‘isTokenValid’, this method will be responsible to receive token and return boolean value whether the token is valid or not.

This is pretty straightforward, we will use the function from ‘jsonwebtoken’ which is called ‘verify’, this method receives the token and the secret key, if the token has been issued by our server or the expiration date is still valid, we will not get an exception.otherwise we will get an exception, therefore we will write this code with try{} catch{}

isTokenValid method implementation

Our last method will be ‘getTokenData’ which will extract the object from the payload, this looks pretty the same as our ‘isTokenValid’ method.

It performs also validation on the token, in case the token is not valid we will throw exception.

getTokenData method implementation

Horrayyyy! we’re almost done, JWTService file is implemented, let’s create simple main function to run all our functionality!

It’s important to talk about this part now, for simplicity of the guide I’ve hardcoded the secret key inside our code, this is really bad practice to do so, the secret key should come from server/cloud configurations!

Let’s import our new service and create a simple function called ‘getConfigurations’ at our Main.js file, this method will receive the payload data as argument, we will set the secret key over here ( but remember that it is not the right way to do it ), and we will set our expiration date to 7 days.

getConfigurations method implementation

Let’s implement the main method which will run automatically when we will run the project, Those are the steps for our main method:

  • We’ll create object which will contain our payload, I’ve decided to create ‘Name’ and ‘Email’ keys in my payload.
  • We will get the configurations including our payload.
  • We will instantiate JWTService and we’ll inject our secret key.
  • And now we will generate new token, validate it and extract your information using the methods we’ve just created.

That’s all, simple eh? :)

If you will clone the repository, please make sure to run “npm install” before you start working on the project since you need ‘jsonwebtoken’ file in your node_modules.
You can view the source code at my GitHub Repository — Click here.

Every comment or feedback is welcome, if it will be necessary I will fix the article / code.

Feel free to contact me directly at LinkedIn — Click Here.

--

--