Using passport.js with multiple strategies without overwriting user request object

不打扰是莪最后的温柔 提交于 2019-12-11 03:54:04

问题


I'm using passport.js local-strategy for auth. I also need users to authenticate with Facebook, Twitter, and G+, but not as auth alternatives, but to enable the user to retrieve their content from those services.

As written, each auth strategy writes a user object to the request object. This has the effect of logging-out my root user. Is there a way to leverage passport for these additional auth strategies, but not override the user object?

Here is the canonical example:

var passport = require('passport')
  , TwitterStrategy = require('passport-twitter').Strategy;

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://www.example.com/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    User.findOrCreate(..., function(err, user) {
      if (err) { return done(err); }
      done(null, user); //trashes my existing user object
    });
  }
));

回答1:


A way to do this is to use a callback rather than a redirect. Usually you would call req.login() to set the request object. You can just skip that step and do whatever you want with the response.

app.get('/auth/twitter/callback', function (req, res, next) {
        passport.authenticate('twitter', function (err, user, info) {
            res.send({err: err, user: user, info: info}); //skip req.login()
        })(req, res, next)
    });



回答2:


This is listed in the Passport docs. http://passportjs.org/guide/authorize/



来源:https://stackoverflow.com/questions/26453527/using-passport-js-with-multiple-strategies-without-overwriting-user-request-obje

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