Passport js authenticate by url

扶醉桌前 提交于 2019-12-13 01:06:09

问题


I'm using Express JS and Passport JS for my app.

I want to give a new user the opportunity to automatically login, once, by a specific URL. I can get the user from the database with the information from the URL, so I have an User object (with id, email, hashed password etc.) but I don't know how I can use passport to authenticate the user and login.

I tried executing below function with the user object I got from the database:

req.login(user, function(err) {
  if (err) { return next(err); }
  return res.redirect('/users/' + req.user.username);
});

source: http://passportjs.org/guide/login/

But that didn't work. Guess it's just because the user object contains the hashed password... Anyone who ever tried this before and can tell me how it works?


回答1:


Maybe https://github.com/yarax/passport-url strategy will be useful for you

Base logic is getting argument from url

UrlStrategy.prototype.authenticate = function(req, options) {
    var self = this;

    function verified(err, user, info) {
        if (err) { return self.redirect(self.failRedirect); } // redirect in fail
        self.success(user, info); // done callback
    }

    this._verify(req.query[this.varName], verified);
};

Full example here https://github.com/yarax/passport-url/blob/master/index.js




回答2:


Heyo, so while @Rax Wunter is totally right, I just saw this question and wanted to say it is NOT A GOOD IDEA to do what you're doing here. You should never be passing a hashed password in a URL string ever. This is a really bad security concern.

What you should do instead is use something like a JSON Web Token (JWT). There are lots of libraries to help with this, but the basic flow goes something like this:

  • Wherever you are generating your URL, you'll instead generate a JWT that contains the user ID in it.
  • You'll then build a URL that looks like: https://somesite.com/?token=
  • On your https://somesite.com endpoint, you'll read in the token, validate it using the JWT library (and a shared secret variable), and this will confirm this token was unmodified (eg: you KNOW this user is who they claim to be).

This strategy above is really great because it means you can safely log someone in, in a trusted way, without compromising security or leaking a password hash at all.



来源:https://stackoverflow.com/questions/28611913/passport-js-authenticate-by-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!