How to do it...

Let's follow the steps below to add JWT authentication to our Angular and Express applications:

  1. First, we will import jwt-express into our /app.js Express configuration and initialize it right after our cookieParser middleware. JWT works with cookieParser by default, but we want to customize its cookie options so that our JWT is not an httpOnly cookie, unlike our session cookie. That way, our client application can perform a logout operation by destroying the JWT itself:
...var auth = require('./middleware/auth');var jwt = require('jwt-express');...app.use(cookieParser(process.env.cookieSecret));app.use(jwt.init(process.env.jwtSecret, {  cookieOptions: {httpOnly: false}}));...
  1. Next, we will update our /routes/login.js route ...

Get MEAN Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.