Learn using JWT with Passport authentication

Arpy Vanyan
Dec 28, 2017 · 4 min read
Image for post
Image for post

Introduction

Almost every web and mobile app nowadays has authentication. Most of them offer different login methods like Facebook, Google or email/password at once.

Passport is a Node.js middleware that offers a variety of different request authentication strategies that are easy to implement. By default, it stores the user object in session.

JSON Web Tokens is an authentication standard that works by assigning and passing around an encrypted token in requests that helps to identify the logged in user, instead of storing the user in a session on the server and creating a cookie. It has different integrations including a Node.js module.

Below is a tutorial about using this two modules together and setting up an authentication on an express based backend. Luckily, Passport allows an option to store the user object in request instead of the session.

The tutorial will use a simple local (email/password) authentication, but it may as well be used with any other strategy.

First, lets install the dependencies.

npm install --save passport passport-local passport-jwt jsonwebtoken

Now here is how everything is going to work:

  • When the user logs in, the backend creates a signed token and returns it in response
  • The client saves the token locally (typically in localStorage) and sends it back in every subsequent request that needs authentication
  • All requests needing authentication pass through a middleware that checks the provided token and allows the request only if the token is verified

So, let’s implement this logic.

Login

Assume we have set up and used the local passport strategy in a separate file next to app.js like this:

//passport.js

We need to require this file in app.js.

//app.js

Now, in our auth.js route file, we’ll implement the login action. Here, we call the passport authentication function with local strategy, handle the errors and log in the user.

//routes/auth.js

Note, that we pass {session: false} in passport options, so that it wont save the user in the session. Also, we create and return a signed JSON web token based on the user object to the client. You can, of course, choose any object to create a token with, as long as it will help you identify your user. The idea is, to store the minimum info that you can use without having to retrieve the user from the database in all the authenticated requests.

Protected requests

Now, we’ll create a middleware, that allows only requests with valid tokens to access some special routes needing authentication, eg. /user/profile. For this, we will use the passport-jwt strategy. We’ll add it in our passport.js file.

//passport.js
...
const passportJWT = require("passport-jwt");
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
...

Note, that we assume that the client will send the JWT token in Authorization Header as a Bearer Token. The Passport JWT Strategy supports many other ways of getting the token from requests. Choose whichever suits your needs.

Now, all we need to do is to use this middleware in our app for the protected routes. For this tutorial, we’ll prepare a simple user route like this:

//routes/user.js

And use the passport authentication middleware on user route as shown below:

//app.js

And that’s it!

Go on and try out some requests, now they’ll be backed with JSON Web Token authorization with Passport 👍

Want more on JWT?

Here is my article on how you can log out the user when authenticating with JWT.

PS. Here are the final files in Gist:

Frontend Weekly

It's really hard to keep up with all the front-end…

Arpy Vanyan

Written by

I’m a coder, a reader, a photographer, a passionate traveler and a cyclist. Currently crafting http://booktrail.co

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Arpy Vanyan

Written by

I’m a coder, a reader, a photographer, a passionate traveler and a cyclist. Currently crafting http://booktrail.co

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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