Introduction to Passport.js and JSON Web Tokens

Get an overview of Passport.js and JSON Web Tokens.

By the end of this chapter, we’ll be able to do the following:

  • Implement sign-up and login functionalities for our Express Recipes API.
  • Authenticate application users’ requests using Passport.js and JSON Web Tokens.

Passport.js overview

Passport.js is an easy-to-integrate middleware used for authentication.

Passport.js offers various authentication mechanisms (known as strategies) as individually-packaged modules. Currently, more than 500 authentication strategies exist in the Passport.js ecosystem. Strategies include verifying a username and password, delegated authentication using OAuth, and federated authentication using OpenID.

In this chapter, we’ll use the Passport.js authentication strategy based on JSON Web Tokens to add authentication to the Express Recipes API.

JSON Web Tokens overview

In REST architectures, client-server interactions are typically stateless. A stateless server doesn’t store any history or state about the client session. After all, server-based sessions are often costly to implement and don’t scale well.

Instead, the session state is often stored on the client, such as in a browser’s cookie, so the client is responsible for transferring all the information needed to execute a request to the server.

JSON Web Token (JWT) is a lightweight and secure approach to transfer the state from the client to the server in a REST framework. JWT (pronounced “JOT”) is an open-standard authentication strategy that relies on exchanging encoded and cryptographically signed JSON strings between client and server.

JWTs allow us to delegate authentication logic to an authorization server. We can delegate login and signup of a cluster of applications to a single authorization server.

To understand how JWT works, let’s consider a typical login flow that uses JWT-based authentication:

Get hands-on with 1200+ tech skills courses.