Search code examples
javascriptnode.jspassport.js

How can I impersonate another user with Passport.js in Node?


Using Passport.js in Node, is there a way for me to allow one user to impersonate another? eg. as an Administrator in the application, I want to be able to log in as another user, without knowing their password.

Most simply, I would be satisfied if I could change the serialized user data (user ID) so when deserializeUser is called it will just assume the identity of the alternate user. I've tried replacing the value at req._passport.session.user and the value at req.session.passport.user but the net effect is just that my session seems to become invalid and Passport logs me out.


Solution

  • Passport provides a req.logIn method in case you want to do the authentication manually. You can use it to login any user even regardless of authentication.

    Here's how you can use it. Have the Admin login normally, who'll have an isAdmin flag set.

    Then place a middleware before passport.authenticate in your login route. This will login the new user based only on their username, if the currently logged in user isAdmin.

    app.post('/login',
    
        function forceLogin(req, res, next) {
            if (!req.user.isAdmin) return next(); // skip if not admin
            User.findOne({
                username: req.body.username    // < entered username
            }, function(err, user) {
                // no checking for password
                req.logIn(user, err => {
                    if (err) return next(err);
                    res.redirect('/users/' + user.username);
                });
            });
        },
    
        passport.authenticate('local'),
        function(req, res) {
            res.redirect('/users/' + req.user.username);
        }
    );
    

    Repro: https://github.com/laggingreflex/so28143064