dcsimg
 

Integrate JSON Web Token Authentication into Single-page Apps

Friday Sep 21st 2018 by Rob Gravelle

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:

C:\Users\blackjacques>node -- version
v8.10.0

C:\Users\blackjacques>npm -- version
5.6.0

Creating the Project

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

  1. Fire up Visual Studio and select File > Add Folder to Workspace…
  2. 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.

  3. 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.
  4. 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.

  5. 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.

  6. 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:

  1. Open the package.json file in the VS Code Editor.
  2. In the package.json file, locate the "scripts" element and add the "start": "nodemon server"line:
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "nodemon server"
    },
    

    If by some chance your package.json file doesn't have a "scripts" element, just add it to the top level:

    {
      "requires": true,
      "lockfileVersion": 1,
      "scripts": {
        "start": "nodemon server"
      },
      "dependencies": {
      ...
    

    Now when we issue the npm start command at the terminal prompt, node will bootstrap the server.js script, that we will create next.

  3. In the VS Code Explorer, click the New File button beside your workspace name and call it "server.js":

  4. In the editor, add the following code to the new server.js file:

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    
    const PORT = 3000;
    
    app.listen(PORT, function(){
       console.log('Server is running on Port',PORT);
    });
    
  5. 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.
  6. 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:

    app.get('/checking', function(req, res){
       res.json({
          "Response": "I hear you loud and clear!"
       });
    });
    
  7. 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

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).

Home
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved