4

我正在尝试使用node-openid(通过passport-google)使用他们的 Google 凭据对我的用户进行身份验证。它在我的开发机器上运行良好,但是当我使用 2 个 dyno 将其部署到 Heroku 时,它会在一个 dyno 处理整个 OpenID 对话时工作,而当对话在一个 dyno 上开始并在第二个 dyno 上完成时它会失败。在这种情况下,我收到以下错误:

2013-01-15T15:18:24+00:00 app[web.2]: Failed to verify assertion (message: Invalid association handle)
2013-01-15T15:18:24+00:00 app[web.2]:     at Strategy.authenticate.identifier (/app/node_modules/passport-google/node_modules/passport-openid/lib/passport-openid/strategy.js:143:36)
...

处理这个问题的正确方法是什么?我是否应该以某种方式将对话状态保存在数据库中,以便两个测功机都可以访问它?

更新:

这是我用来通过将关联存储在 MongoDB 中来解决问题的代码。

var
  GoogleStrategy = require('passport-google').Strategy;

// We have to save the OpenID state in the database so it's available to both
// dynos.

db.collection('OpenID').ensureIndex({expires: 1}, {expireAfterSeconds: 0},
    function(err, result) {
        if (err) {
            throw new Error('Error setting TTL index on OpenID collection.');
        }
    });

// Use the GoogleStrategy within Passport.
//   Strategies in passport require a `validate` function, which accept
//   credentials (in this case, an OpenID identifier and profile), and invoke a
//   callback with a user object.
strategy = new GoogleStrategy({
    returnURL: 'http://localhost:3000/auth/google/return',
    realm: 'http://localhost:3000/'
  },
  function(identifier, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's Google profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Google account with a user record in your database,
      // and return that user instead.
      profile.identifier = identifier;
      return done(null, profile);
    });
  }
);

strategy.saveAssociation(function(handle, provider, algorithm, secret, expiresIn, done) {
    db.collection("OpenID").insert({
        handle: handle,
        provider: provider,
        algorithm: algorithm,
        secret: secret,
        expires: new Date(Date.now() + 1000 * expiresIn)
    }, done);
});

strategy.loadAssociation(function(handle, done) {
    db.collection("OpenID").findOne({handle: handle}, function (error, result) {
        if (error)
            return done(error);
        else
            return done(null, result.provider, result.algorithm, result.secret);
    });
});
4

1 回答 1

5

您可能应该查看 node-openid README 中的存储关联状态部分。默认情况下,会话状态存储在各个测功机的内存中,这就是导致您出现问题的原因。

覆盖saveAssociation()loadAssociation()mixins 以使用您的应用程序当前正在使用的任何后备存储。在 passport-openid 源代码中有更多文档。

于 2013-01-15T21:34:09.333 回答