Codementor Events

Express.js Quick Tip: Adding Support for JWT Authentication

Published Apr 06, 2016Last updated Jan 18, 2017

Featured photo

Basics of JWT

JWT is short for JSON Web Token, and is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. You can read all about JWT over at jwt.io

Prerequisites

In this writeup, I am assuming that you already familiar with how to build an ExpressJS app with one or several routes serving requests, and now you want to protect all or some of them with JWT authentication.

Choosing JWT transport

In order to communicate the JWT token between client and server, it naturally needs to be passed along with any and all requests the client performs to the authenticated resources.

There are several options to do that, one is using a cookie, another is using the Authorization header (with a Bearer or JWT scheme) or by simply passing it in a POST or GET parameter (discouraged). Choose the method most appropriate for your use-case.

Verifying Your JWT token

To verify the token, you can use the excellent jwt-async NPM package, configured with the JWT issuers secret or public signing key. Once verified, you have access to the claims set by the issuer of the token.

The following example extracts a JWT token from the Authorization header if it has a JWT scheme, verifies it, and passes it along as the jwt_auth property of req.

First, set up your ExpressJS app

var express = require('express');
var app = express();

Second, add JWT initialization and middleware:

var JWT = require('jwt-async'),
    jwt = new JWT();
jwt.setSecret('secret');

app.use(function(req,res,next) {
  req.jwt_auth = false;
  if(req.headers['authorization'] && 
    req.headers['authorization'].startsWith('JWT')){
      var jwt_token = req.headers['authorization'].substr(4);
      jwt.verify(jwt_token, function(err, jwt_data) {
        if(err) throw err;
        req.jwt_auth = jwt_data;
        next();
      });
    } else {
        next();
    }
});

Third, add some protected route:

app.get('/', function(req, res) {
  if(!req.jwt_auth) {
    return res.redirect('/login');
  }
  res.send('hello', req.jwt_auth.name);
});
Discover and read more posts from Mattias
get started
post commentsBe the first to share your opinion
Show more replies