5

我正在为 Passport with Express 使用 Passport-Linkedin 策略,以允许用户使用他们的 LinkedIn 个人资料登录。

我有以下代码:

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 台机器进行开发)。

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

谢谢!

4

3 回答 3

9

老问题,可能只对较新版本有效。但是,如果有人像我一样遇到这种情况,解决方案就是不在以下文件中指定主机名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
  },
于 2015-04-14T10:19:44.753 回答
0

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

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

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

不确定您的上下文中是否有 req 对象。

于 2012-10-13T04:04:35.687 回答
0

最终通过从 URL 和实际端口动态构建回调 URL 解决了这个问题。对此解决方案不满意,因为它看起来不优雅,但是如果不添加中间件使用调用(我确信这比简单的字符串连接更能影响性能),就无法找到获取实际 URL 的方法。

于 2012-10-15T18:11:59.017 回答