2

This questions has been asked in all kinds of ways but I am not getting an exact answer for my issue.

Router 1

router.post('/user', (req, res, next) => {
    passport.authenticate('local', function(err, user, info) {
        if (err) { 
            return next(err);
        }
        if (!user) { 
            return res.send(info);
        }
        req.logIn(user, function(err) {
          if (err) { 
              return next(err); 
            }
          console.log(req.isAuthenticated()) //return true
          return res.redirect('/myprofile/' + user.username);
        });
      })(req, res, next);
});

The redirected URL will make a call in a different router.

router.get('/:username', (req, res) => {
   console.log(req.isAuthenticated()) // return false
   UserDetails.findOne({
       username: req.params.username
   }, (err, data) => {
       if(err) {
          res.status(400).send('Couldnt fetch details'); //define errs.
       } {
          res.render('dashboard/dash', {
            firstname: data.firstname,
            lastname: data.lastname
          }); 
       }

   })
});

The value of isAuthenticated changes.

What possibly am I missing?

Index

// Express Session Middleware
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  cookie: { secure: true }
}));

//Passsport Middleware
app.use(passport.initialize());
app.use(passport.session());

app.get('*', function(req, res, next){
  res.locals.user = req.user || null;
  next();
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shah Rukh K
  • 559
  • 1
  • 5
  • 19
  • are you trying with https (I'm asking because if `cookie: {secure: true}}` is set, the session cookie only works with https.) – griFlo Jul 19 '19 at 09:14
  • You need to look into this answer, It might similar to your question [req.isAuthenticated() doesn't work](https://stackoverflow.com/questions/29111571/passports-req-isauthenticated-always-returning-false-even-when-i-hardcode-done) I hope it helps. Happy Coding :) – Neel Rathod Jul 19 '19 at 07:23

1 Answers1

0

have you tried this method ?

 passport.authenticate(strategyname)

i have used this with passport with saml

Eitank
  • 570
  • 8
  • 21