JWT Authentication with Node.js and Express

Source: Traversy Media

Introduction

A JSON Web Token (JWT) is a JSON object that’s defined in RFC 7519 as a safe way to represent a set of information between two parties. The token is composed of a header, a payload, and a signature. JWT is used for authentication, and they can also be used for sharing information. Most JWT are signed using a public key and a private key; therefore, it’s very difficult to tamper with these tokens.

Using JWT with Node.js

In this tutorial, we’ll be creating a simple Express app to manage a list of our favorite movies. There will be two types of users — admin and members. Admin will be able to create new movies, whereas members will only have read-access. This could be extended for the remainder of the CRUD functionality but for simplicity’s sake we’ll stick with just the Create action.

$ npm init -y$ npm install --save express body-parser jsonwebtoken

Authentication

Now we’ll create a request handler to handle a user login request. First we create a secret to sign the JWT token that we’ll create after a successful login. The more complex this access token is, the more secure your application will be. So try to use a complex random string for this token.

Authorization

Next we’ll create a simple route to retrieve all movies from our ‘database’.

Authorization: Bearer <token>

Conclusion

In this article, we have introduced you to JWT and how to implement JWT with Express. This is by no means a fully comprehensive authentication solution but this should be enough to get you up and running. For further improvements, I’d recommend having your tokens expire as in this implementation if a token were to be stolen that would allow limitless access. To do this you’ll need to create a separate JWT token, a refresh token, which can then be used to generate a new access token.