• 10 hours
  • Medium

Free online content available in this course.



Got it!

Last updated on 4/28/21

Set up authentication middleware

Log in or subscribe for free to enjoy all this course has to offer!

Implement authentication middleware

We are now going to create the middleware which will protect selected routes, and ensure that a user is authenticated before allowing their requests to go through.

Create a new  middleware  folder, and an  auth.js  file inside it:

const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
const userId = decodedToken.userId;
if (req.body.userId && req.body.userId !== userId) {
throw 'Invalid user ID';
} else {
} catch {
error: new Error('Invalid request!')

In this middleware:

  • because many things can go wrong, we are putting everything inside a  try...catch  block

  • we extract the token from the incoming request's  Authorization  header — remember that it will also contain the  Bearer  keyword, so we use the split function to get everything after the space in the header — and any errors thrown here will wind up in the  catch  block

  • we then use the  verify  function to decode our token — if the token is not valid, this will throw an error

  • we extract the user ID from our token

  • if the request contains a user ID, we compare it to the one extracted from the token — if they are not the same, we throw an error

  • otherwise, all is well, and our user is authenticated — we pass execution along using the  next()  function

Now we need to apply this middleware to our  stuff  routes, which are the ones we want to protect.  In our  stuff  router:

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const stuffCtrl = require('../controllers/stuff');
router.get('/', auth, stuffCtrl.getAllStuff);
router.post('/', auth, stuffCtrl.createThing);
router.get('/:id', auth, stuffCtrl.getOneThing);
router.put('/:id', auth, stuffCtrl.modifyThing);
router.delete('/:id', auth, stuffCtrl.deleteThing);
module.exports = router;

We simply import our middleware and pass it as an argument to the routes we wish to protect.

Now, from the front end, you should be able to login and use the app normally.  To check that unauthorized requests do not work, you can use an app like Postman to pass a request without an  Authorization  header — the API will refuse access and send a 401 response.

Congratulations!  Your API now implements token-based authentication, and is properly secure.

Let's recap!

In this part of the course:

  • you added a User data model in order to store user information in your database;

  • you implemented secure password encryption so as to safely store user passwords;

  • you created and sent JSON web tokens to the front end to authenticate requests;

  • you added authentication middleware to secure routes in your API, meaning that only authenticated requests would be handled.

In the final part of this course, you will learn how to handle files:

  • how to capture files coming in from the front end;

  • how to save them to your server;

  • and how to delete them when they are no longer needed.

Example of certificate of achievement
Example of certificate of achievement