Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

const jwt = require('jsonwebtoken');
const passport = require('passport');
const passportJWT = require('passport-jwt');
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
const jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
jwtOptions.secretOrKey = 'movieratingapplicationsecretkey';

const app = express();
const router = express.Router();

The preceding code is enough to get us started. We will need


JwtStrategy from passport.js, and ExtractJwT will be used to extract the payload


data in the jwt token.


We have also defined a variable to set the JWT auth settings, which has a secret key


configured. This secret key will be used to sign the payloads of any requests.


You can also create a separate file to store your important keys.


Using the JWT strategy


Now we are all set up to use the services provided by passport.js. Let's quickly recap


what we have done so far:



  1. Installed passport, passport-jwt, and jsonwebtoken

  2. Configured all settings for these three packages


The next steps are as follows:



  1. Creating our user model

  2. Creating API endpoints for the user entity, that is, sign in and sign up

  3. Building our authentication views, that is, the login page and register page

  4. Using the JWT strategy to finally authenticate the requests


Setting up user registration


Let's start with adding the functionality to sign up users to our app.

Free download pdf