Integrate JSON Web Token Authentication into Single-page Apps

JSON Web Tokens (JWT) are one of the most widely used authentication mechanisms in modern SPAs. In this article, Rob Gravelle shows us how to set up a SPA in MS Visual Source Code. Within that development environment, we'll build and test an SPA that authenticates a user's credentials against one that is stored securely in a MongoDB database.

There are basically two types of authentication you can use in any web app: Session-based and Token-based. For today's single-page apps (SPAs), Session-based authentication tends to be overkill. Therefore, Token-based authentication is the de facto standard for SPAs. JSON Web Tokens (JWT) are one of the most widely used in modern SPAs. JWT is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using a cryptographic algorithm such as RSA or ECDSA.

In today's article, we'll set up a Node.js project in MS Visual Source Code. Within that development environment we'll build and test an SPA that authenticates a user's credentials against one that is stored securely in a MongoDB database.

Prerequisites

In order to follow along with this tutorial, you'll want to download MS Visual Studio Code, as well as the Node.js JavaScript runtime and npm Node.js package manager. Node.js comes with npm, so installing it covers both tools.

To confirm that you have Node.js and npm correctly installed on your machine, you can type the following statements at the command prompt:

Creating the Project

The first thing we'll need is a folder in which to put all of our project files.

Fire up Visual Studio and select File > Add Folder to Workspace…

That will bring up a folder browser that you can use to select the project folder. You don't have to create one before-hand. In Windows, you can just use the New Folder button to create one.

With the project folder added, go to the Terminal and make sure that the working directory is your project root. If the Terminal is not currently visible, go to View > Integrated Terminal to bring it up.

In the Terminal, type the following command:

npm init

That will initiate a command line questionnaire that will conclude with the creation of a package.json in the directory in which you initiated the command.

Alternatively, you can issue:

npm init -- yes

That will generate a default package.json using information extracted from the current directory.

Now it's time to install some dependencies:

npm install express jsonwebtoken mongoose body-parser -- save

That will install the express web framework, jsonwebtoken package to authenticate the user, mongoose schema model, and body-parser middleware.

We also need to install the nodemon development server to prevent the stopping and restarting of the server process.

npm install nodemon -- save-dev

That's all we need for now. We'll be adding a few more dependencies as we go.

Configuring the Node Server

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. It wraps your application, so you can pass all the arguments you would normally pass to your app. We'll tell it to start our server:

Open the package.json file in the VS Code Editor.

In the package.json file, locate the "scripts" element and add the "start": "nodemon server"line:

That's all it takes to get the server configured. To start the server, go to the Terminal and issue the npm start command. You'll see the "Server is running on Port 3000" message in the console.

If you try to bring up in the browser, you'll get a "Cannot GET /" message because our simple server is not set up to fetch a default resource like index.html. Let's get rid of that error by defining a route that will send a JSON response back to the client:

In your browser of choice, navigate to http://localhost:3000/checking. You should see the {"Response":"I hear you loud and clear!"} JSON-formatted server response:

Going Forward

We'll leave it at that for now. You can peruse the files that we worked on today on GitHub.

Next time, we'll:

Set up the MongoDb database.

Create a User model.

Create the Signup Route.

And, last but not least, add the authorization code!

Rob Gravelle resides in Ottawa, Canada. His design company has built web applications for numerous businesses and government agencies. Email him.

Rob's alter-ego, "Blackjacques", is an accomplished guitar player, who has released several CDs and cover songs. His band, Ivory Knight, was rated as one of Canada's top hard rock and metal groups by Brave Words magazine (issue #92).

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.