如何设置当前主机的Passport策略callbackURL?

我正在使用Passport with Express的Passport-Linkedin战略,允许用户使用他们的LinkedIn个人资料login。

我有以下代码:

passport.use(new LinkedInStrategy({ consumerKey: config.linkedin.LINKEDIN_API_KEY, consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, callbackURL: "http://localhost:3000/auth/linkedin/callback" }, function(token, tokenSecret, profile, done) { // asynchronous verification, for effect... process.nextTick(function () { // To keep the example simple, the user's LinkedIn profile is returned to // represent the logged-in user. In a typical application, you would want // to associate the LinkedIn account with a user record in your database, // and return that user instead. return done(null, profile); }); } )); 

在第4行,我必须手动设置完整的callbackURL。 我有一个生产线和一个用于开发的string,但是我的URL不断变化,端口也是这样(我使用2台机器来开发)。

如何自动设置URL的第一部分( http://localhost:3000 )? 是否有expressapp的财产,将允许我这样做? 我需要求助于一个app.use(function(req, res){});

谢谢!

老问题,可能y答案只适用于较新的版本。 但是,如果有人遇到这个问题,就像我一样,解决方法就是不在callbackURL指定一个主机名:

 passport.use(new LinkedInStrategy({ consumerKey: config.linkedin.LINKEDIN_API_KEY, consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, callbackURL: "/auth/linkedin/callback" }, 

为了让这个工作适用于heroku httpsredirect,我们必须通过信任代理来告诉系统信任x-forwarded-protocol头信息:

 passport.use(new LinkedInStrategy({ consumerKey: config.linkedin.LINKEDIN_API_KEY, consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, callbackURL: "/auth/linkedin/callback", proxy: true }, 

最终通过dynamic构build来自URL和实际端口的callbackURL解决了这个问题。 不喜欢这个解决scheme,因为它看起来不够优雅,但找不到一个方法来获得实际的URL,而不添加中间件使用调用(这肯定会影响性能而不是简单的string连接)。

在我的config.js我有一个cfg.site_url,这是一种方式,或者你可以看看req.host

http://expressjs.com/api.html#req.host

 // Host: "example.com:3000" req.hostname // => "example.com" 

不知道你的上下文中是否有req对象。