JWT Authentication in Express.js

Introduction

+-- package.json
+-- app.js
+-- middlewares.js
+-- libs
| +-- auth.js
+-- models
| +-- User.js
| +-- index.js (exports all the files)
+-- routes
| +-- auth.js
| +-- dashboard.js
| +-- index.js (exports all the files)

Understanding the structure

  • libs directory stands for libraries. All the logic goes there.
  • models is where we store all the DB models, mongoose in my case. Not much related JWT happens there.
  • routes is self explanatory — all the routes are stored there. Auth in this case.

Baby Steps

libs/auth.js

Verifying the Token

Creating new Token

  • algorithm (default: HS256)
  • expiresIn: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, "2 days", "10h", "7d"
  • notBefore: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, "2 days", "10h", "7d"
  • audience
  • issuer
  • jwtid
  • subject
  • noTimestamp
  • header

Export Default

Implementation!

middleware.js

routes/auth.js — login

  1. we query database for the user
  2. we compare provided password, with the one in the returned document’s
  3. we convert our Mongoose model into JSON format and strip it off, of any confidential data.

routes/dashboard.js

  1. user tries to access the dashboard
  2. user is verified for his token
    a) token is provided and is valid — user get’s passed in,
    b) token is either not provided or is invalid — middleware cuts in, and responds with status 400.

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store