× {{alert.msg}} Never ask again
Online JavaScript Course Master JavaScript in 4 Weeks
View Class

Express.js Quick Tip: Adding Support for JWT Authentication

– {{showDate(postTime)}}
Express.js Quick Tip: Adding Support for JWT Authentication

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);
});


Author
Mattias
Mattias
5.0
Coding addict since age 10 I now master many things
Currently Javascript is my dope, both in the browser and using NodeJS. I know many protocols, patterns, coding styles, operating environments and languages. I have partaken in multiple company...
Gigs Mattias can do for you:
Arduino development introduction
Advice on optimizing page load speed
Setup of DigitalOcean droplet ready for docker deployments

Questions about this tutorial?  Get Live 1:1 help from JavaScript experts!
David Sparks
David Sparks
4.9
Custom Web Developer
My name is David - I have been working with and building web based applications for years using the PHP OOP framework, WordPress, HTML and CSS....
Hire this Expert
Alexander Luberg
Alexander Luberg
5.0
Expert full-stack developer(Python/ES6/React/Redux) with 8+ year of experience. @LinkedIn
Sr. Software Engineer @ LinkedIn, 8+ years of experience
Hire this Expert

Or Become a Codementor!

Online javascript training course live
Online JavaScript Course
Master JavaScript in 4 Weeks
comments powered by Disqus
Online JavaScript Course
Master JavaScript in 4 Weeks