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

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

Simply put, I would be happy if I could change the serialized user data (user id), so when deserializeUser is deserializeUser , it will just accept the alternate user id. I tried replacing the value with req._passport.session.user and the value in req.session.passport.user , but the net effect is only that my session seems invalid and Passport disconnects me.

+6
source share
3 answers

The passport provides the req.logIn method if you want to authenticate manually. You can use it to log in to any user, even regardless of authentication.

You can use it here. As a rule, the administrator has a username that will have the isAdmin flag isAdmin .

Then put the middleware before passport.authenticate in your login. This will log in a new user, based only on the username if the current 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); res.redirect('/users/' + user.username); }); }, passport.authenticate('local'), function(req, res) { res.redirect('/users/' + req.user.username); } ); 
+9
source

I have another way to personalize, because:

  • I did not want to mess with internal authentication / passport session storage / logIn / etc. You must understand them well and they are subject to change, so I would say that this is not an option for me.
  • In addition, I would also like to know if the action was performed from superuser (impersonated) or regular user (not impersonated).

What am I doing:

  • Do you have a route for a user with the superadmin role to impersonate, for example /superadmin/impersonate?username=normaluser1 , which sets req.user.impersonated.userid = normaluser1.userid

  • Then I have middleware that checks if the user is a super admin and pretends to be:

    if (req.user.isAdmin & req.user.impersonated) {req.user.userid = req.user.impersonated.userid; }

In addition, I found this to be a good article about impersonating a user. Like my approach, and good for inspiration to create something like that.

+2
source

The answer to your question is basically: no. The reason is that the session library, which is used in 99% of cases, signs cookies, so if you break the data, the web server will reject them.

How to do this, you need to write your own passport authentication strategy, which obviously does not do this, but I assume that you are talking about working with built-in strategies here.

+1
source

Source: https://habr.com/ru/post/981526/


All Articles