Chapter 11. Authenticating users, managing sessions, and securing APIs

 

This chapter covers

  • Adding authentication in the MEAN stack
  • Using Passport to manage authentication in Express
  • Generating JSON Web Tokens in Express
  • Registering and logging in a user
  • Securing API endpoints in Express
  • Using local storage and Angular to manage a user session

In this chapter we’re going to improve upon the existing application by making users log in before they can leave reviews. This is an important topic, as many web applications need to let users log in and manage a session.

Figure 11.1 shows where we’re at in the overall plan, now working with the MongoDB database, Express API, and Angular single-page application.

Figure 11.1. This chapter adds an authentication system to the application that touches most parts of the architecture, such as the database, API, and front-end SPA.

Our first stop will be an overview of how to approach authentication in a MEAN stack application, before updating Loc8r one piece at a time, working through the architecture from back to front. So we’ll update the database and data schemas first, before upgrading the API, and finally modifying the front end. By the end of the chapter we’ll be able to register new users, log them in, maintain a session, and do actions that only logged-in users can complete.

11.1. How to approach authentication in the MEAN stack

11.1.1. Traditional server-based application approach

11.1.2. Full MEAN stack approach

11.2. Creating a user schema for MongoDB

11.2.1. One-way password encryption: Hashes and salts

11.2.2. Building the Mongoose schema

11.2.3. Setting encrypted paths using Mongoose methods

11.2.4. Validating a submitted password

11.2.5. Generating a JSON Web Token

11.3. Creating an authentication API with Passport

11.3.1. Installing and configuring Passport

11.3.2. Creating API endpoints to return JSON Web Tokens

11.4. Securing relevant API endpoints

11.4.1. Adding authentication middleware to Express routes

11.4.2. Using the JWT information inside a controller