Summary

While this approach may work well in many situations, you often find that you'll need to extend capabilities, so you'll soon roll up your sleeves and start bending some code. The fun stuff!

This article will share an approach for adding authentication to a json-server using a simple, unobtrusive Express middleware component called Passport.

Architecture

Most sites require users to register and then use their credentials for access. Passport provides the layers necessary for authenticating claims made by users logging in to the site.

User Registration

Basic Authentication is the simplest form of authenticating users, consisting of a username and a secret password. Being the simplest, it's arguably also the weakest form and vulnerable to intercept and exploitation when not used with secure transports.

The intent of this article is to share how we can start moving from plain text unauthenticated methods of communicating with our json-server to more robust solutions. Passport provides an extensible set of plugins known as strategies which will help you to do just that. At the time of writing this article, there are nearly 500 authentication strategies to choose from including:

Basic Authentication

Facebook

Twitter

Google

LinkedIn

Strategies can range from verifying a username and password credentials, delegated authentication using OAuth (using Facebook or Twitter), or federated authentication using OpenID.

We'll now integrate passport authentication with the json-server we created in the last article.

CAUTION: For the sake of brevity and focusing on authentication, this example doesn't use TLS as any real-world application should.

Configuring User Authentication

Passport author Jared Hanson provides us with many a good example of Strategy implementation; and, as good OO practitioners we'll follow the mantra to reuse rather than reinvent, leveraging his Basic Authentication example.

Our new folder hierarchy now includes a db folder, simulating a database containing authentication credentials.

Configuring npm Packages

In our earlier Zero Code example, we were able to start the json-server with staticassets in our project hierarchy. As we add custom code, we'll need a way of letting npmknow about our project dependencies. This is accomplished by adding package.json.

Configuring Server.json

Our customized rendition of json-server allows for additional middleware products in our json-server implementation. To add the Basic Authentication support, we start with the sample code described in the Module section of the json-server website and add our references to Passport.