Ed Lynch
Ed Lynch

Reputation: 623

Save a JWT as a cookie

so basically I want to store a JWT token in a cookie so that it can be accessed later to authenticate API calls. I can't figure out how to do this.

 passport.use(new LocalStrategy(
      function(email, password, done) {
       User.getUserByEmail(email, function(err, user){
        if(err) throw err;
        if(!user){
            return done(null, false, {message: 'Unknown User'});
        }

        User.comparePassword(password, user.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch){

            const token = jwt.sign(user, config.secret, {
              expiresIn: 604800 // 1 week
            });

                    //STORE TOKEN AS A COOKIE

                return done(null, user);
            } else {
                return done(null, false, {message: 'Invalid password'});
            }
        });
       });
        }
    ));
    router.post('/login',
      passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
      function(req, res) {
        res.redirect('/');
      });

Thanks in advance, Ed.

Upvotes: 0

Views: 4897

Answers (1)

Stephen L
Stephen L

Reputation: 2339

After reading the documentation, it seems like this might not be the best place to set jwt cookies. In order to do so, you need access to the response object. Perhaps you could set the cookie using another middleware function just after your authentication middleware in your POST route?

   router.post('/login',
      passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
      setJWTFn, //insert middlelware here
      function(req, res) {
        res.redirect('/');
      });

where the setJTWFn looks something like:

function setJWTFn(req, res, next) {
   //create JWT
  const jwt = createJWT();
  res.cookie('jwt', jwt);
  next();
}

Upvotes: 4

Related Questions