【问题标题】:How to use Github Oauth for Nodejs?如何为 Nodejs 使用 Github Oauth?
【发布时间】:2015-02-28 12:07:50
【问题描述】:

我已经从 Github、npm 模块和 SO 上的类似问题的说明中剪切并粘贴了每个代码块。不管怎样,解决方案都行不通。我正在使用 Ubuntu 14.04、Nodejs Express 和 Postgresql。我想我只是不知道我现在在做什么。这是我目前遇到的错误:

我倾向于认为我的代码有问题,并且这个错误是由于这个而不是实际模块的失败。无论如何,我已经向作者报告了,以防万一。这是 app.js 中的代码:

// POSTGRESQL AUTHORIZATION FUNCTION
var findOrCreate = function(username,id) {
if (db.query("SELECT EXISTS(select username from users where github_id="+id)) {
    passport.authenticate('local');
    res.redirect('/', { user: req.user });
} else {
    db.query("INSERT INTO users (username, github_id) VALUES ($1, $2)"), [username, id], function(err, res) {
        if (!err) {
            passport.authenticate('local');
            res.render('/', { user: req.user });
        }
        console.log(err);
    };
}
};

// GITHUB AUTHENTICATION
passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://localhost:5000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function() {
        console.log("Access Token: " + accessToken);
        console.log(profile.username);
        findOrCreate(profile.username, profile.id);
        return done(null, profile);
    });
}));

在 Google Chrome 的控制台中,当我尝试使用 Github 登录时,我收到了 ERR_CONNECTION_REFUSED

我正在尝试通过 Github 授权登录,请根据我数据库中的 users 表检查 Github 凭据。如果在数据库中找到用户,请使用找到的凭据登录。如果没有,请存储他们的用户数据并登录。

我在这里做错了什么?

【问题讨论】:

  • ERR_CONNECTION_REFUSED 很可能意味着后端出现错误导致服务器重新启动。你能从终端复制错误吗
  • @teleaziz 该错误来自浏览器控制台。我正在使用谷歌浏览器。 OP 中显示了终端错误。起初我以为这是一个繁忙的端口问题,但似乎并非如此,尽管我可能错了。谢谢!

标签: node.js authentication express


【解决方案1】:

我假设您使用的是 node-postgres 模块 pg , pg.query 接受回调,所以让我们利用这个功能并实际分离关注点:

我也非常推荐使用passport-github2 模块来维护 github oauth 策略并保持最新:

var findByGithubId= function(githubId, callback) {
  return db.query('SELECT * FROM "users" WHERE github_id = $1', [githubId], callback);
};

并创建:

var createOne = function(username, githubId, callback){
  return  db.query("INSERT INTO users (username, github_id) VALUES ($1, $2)", [username, githubId], callback);
};

为 github 定义护照处理程序:

var passportGithubHandler = function(accessToken, refreshToken, profile, done) {
  findByGithubId( profile._json.id, function(err, user) {
    if (!user) {
      createOne(profile._json.name , profile._json.id , function(err, result){
        if (err) done(err);
        user= result.rows[0]; // not sure about this one please investigate, console.log might help 
        return done(err, user);
      })
    } else {
      return done(err, user);
    }
  });
};

传递处理程序:

passport.use(new GitHubStrategy({
  clientID: GITHUB_CLIENT_ID,
  clientSecret: GITHUB_CLIENT_SECRET,
  callbackURL:"http://localhost:5000/auth/github/callback"
},
passportGithubHandler));

然后定义路由去认证

app.get('/auth/github',
  passport.authenticate('github'));

还有回调路由

app.get('/auth/github/callback', 
  passport.authenticate('github', { failureRedirect: '/login' }),
  function(req, res) {
      // render or redirect or do whatever you have access to req.user now
    res.redirect('/'); 
  });

【讨论】:

  • 非常感谢这次故障。按原样使用此代码会给我一个序列化错误:Failed to serialize user into session。看起来这是因为我的序列化处理程序不处理 github_id,只处理常规用户 ID,但我不确定如何修改它以使其工作。这是我的护照序列化代码的link。我只是添加user.github_id吗?
  • 编辑:发现一个问题。这些处理程序不会对任何人进行身份验证。我检查了数据库,运行此代码后没有新用户。 Github 也没有要求我授权登录。所以我现在不确定发生了什么。
猜你喜欢
  • 2013-01-22
  • 1970-01-01
  • 2015-02-13
  • 2014-10-29
  • 2021-01-27
  • 2012-11-06
  • 2019-11-26
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多