如何使用相同的Twitter应用程序使用来自一个域的多个主机名进行身份验证?

时间:2012-08-16 18:57:24

标签: node.js twitter express twitter-oauth passport.js

我的DNS有两个主机名被发送到同一个IP:

  • theark.info
  • www.theark.info

我使用theark.info在我的Twitter应用中明确设置了回调和域名。确保我可以使用www.theark.info为Oauth使用相同的Twitter应用程序的最佳方法是什么,因为我目前收到错误:

  

内部服务器错误

在我的DNS中,我的DNS中有一个CNAME www,指向theark.info

也许我需要使用Express和Javacsript对请求操纵DOM?

1 个答案:

答案 0 :(得分:2)

您无法更改Twitter(或任何其他OAuth提供商),它们都只提供一个回调到一个域。一个简单的解决方案是将所有请求从http://domain.com重新路由到http://www.domain.com,以便所有访问者在进行身份验证之前最终访问www.domain.com。您应该可以在DNS上或使用req.header重定向服务器端执行此操作:

app.get('/*', function(req, res, next) {
  if (req.headers.host.match(/^www/) !== null ) {
    res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
  } else {
    next();     
  }
})

this answer复制。

使用passport.js进行身份验证时,请尝试指定回调网址:

passport.use(new TwitterStrategy({
    consumerKey: auth_keys.twitter.consumerKey,
    consumerSecret: auth_keys.twitter.consumerSecret,
    callbackURL: auth_keys.twitter.callbackURL
  },
  function(token, tokenSecret, profile, done) {
    process.nextTick(function () {
      User.twitterAuth({ profile: profile }, function (err, user) {
        return done(err, user);
      });
    });
  }
));

确保callbackURL与Twitter中配置的完全相同。如果您在localhost上运行节点进行开发,请尝试两个不同的密钥文件,并在twitter上创建另一个身份验证应用程序,其中127.0.0.1:3000作为回调地址。您可以切换开发和生产的关键文件:

if (app.get('env') == 'development') {
  auth_keys = require('./lib/keys_dev');
} 
if (app.get('env') == 'production') {
  auth_keys = require('./lib/keys_live');
}