Passport Authenticate doesn't redirect

前端 未结 2 1164
说谎
说谎 2021-01-28 15:54

I was writing a local-signup strategy and noticed that it doesn\'t work so I stepped back and tried to authenticate against my empty collection. Every time I submit the form it

相关标签:
2条回答
  • 2021-01-28 16:08

    After a quick look at the documentation for passportjs, I think you need to do something like this:

    function processSignup (req, res, next) {
        logger.info("POST request received")
        logger.info(req.body)
        const handler = passport.authenticate('local', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/signup', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        });
        handler(req, res, next);
    }
    

    passport.authenticate() returns a function that is meant to be used as the route handler function.
    Normally, you would type something like:

    app.post('/login', passport.authenticate('local', {
      successRedirect: '/',
      failureRedirect: '/login',
      failureFlash: true 
    }));
    

    But since you have abstracted with your own route handler function, you need to invoke the one returned from passport.authenticate().

    0 讨论(0)
  • 2021-01-28 16:30

    In the end Mikael Lennholm was right and he pointed me into the right direction. I couldn't find that in any passport.js tutorials. However the passport.js documentation contains this code snippet which represents the same but I prefer it's code style:

    passport.authenticate('local', function(err, user, info) {
        if (err) { return next(err); }
        if (!user) { return res.redirect('/login'); }
        req.logIn(user, function(err) {
          if (err) { return next(err); }
          return res.redirect('/users/' + user.username);
        });
      })(req, res, next);
    
    0 讨论(0)
提交回复
热议问题