2012-10-13 90 views
5

我使用Passport with Express的Passport-Linkedin战略,允许用户使用其LinkedIn个人资料登录。如何设置Passport策略的当前主机策略callbackURL?

我有以下代码:

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行中,我必须手动设置全回调URL。我有一个字符串用于生产,一个用于开发,但我的URL不断变化,端口也一样(我使用2台机器开发)。

如何自动设置URL的第一部分(http://localhost:3000)?是否有expressapp的财产可以让我这样做?我需要使用app.use(function(req, res){});吗?

谢谢!

回答

4

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

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

为了得到这个为Heroku的https使用重定向,我们必须告诉系统信任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 
    }, 
+2

如果您的应用程序未在根路径上运行,则不起作用,例如,它在'/ myapp'而不是'/'上运行。 –

0

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

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

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

不知道如果你有一个REQ对象的上下文。

+0

我开始使用配置字符串,但服务器名称和端口不断变化。我在应用程序级别 - 据我所知,获得req的唯一方法是添加我提到的app.use语句。问题是,它会被每个请求调用。 –

+0

您可以为您的请求提供中间件。类似于app.get('/ whatever',loadConfigVariable,routes.whatever);'和'app.locals.whatever = config.whatever'内部的loadConfigVariable函数。 – chovy

+0

这就是我试图避免的 - 另一条路线。我想知道我是否可以在Passport本身中找到这个功能? –

0

最终通过动态构建URL部分和实际端口的回调URL解决了这个问题。因为它看起来不够优雅,所以对这个解决方案并不满意,但是找不到一个在不添加中间件使用调用的情况下获得实际URL的方法(我确信这比性能更强,而不是简单的字符串连接)。