Exercise 20: Adding User Authentication

Now that we have secured all our todo routes, we need a way to issue tokens to valid users to access the API. We will have the users send their email and password to a route (/auth), and our API will issue back an authentication token which will be used for each request:

  1. In the /routes folder, create a file auth.js.
  2. We will now need two more packages for this, jsonwebtoken for signing the authentication token, and md5 for comparing the password since if you recall, we were using MySQL's md5 function to store the user's password:
npm install jsonwebtoken md5 --save
  1. In the auth.js file, have the following code:
const jwt = require('jsonwebtoken');const Joi = require('joi');const md5 = require('md5'); ...

Get Beginning API Development with Node.js now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.