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

Ehe*_*Tov 5 twitter node.js twitter-oauth express passport.js

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

  • theark.info
  • www.theark.info

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

内部服务器错误

在我的DNS CNAME www中,我的DNS指向了theark.info

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

Pat*_*ick 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();     
  }
})
Run Code Online (Sandbox Code Playgroud)

从此答案复制。

使用 Passport.js 进行身份验证时,尝试指定回调 url:

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);
      });
    });
  }
));
Run Code Online (Sandbox Code Playgroud)

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

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