【问题标题】:Google Plus Authentication Callback Not workingGoogle Plus 身份验证回调不起作用
【发布时间】:2018-05-24 23:34:41
【问题描述】:

我已添加 Google + 登录,但回调似乎不起作用。

注意:代码改编自本教程:https://scotch.io/tutorials/easy-node-authentication-google

情景

  1. 我去网址:https://gym-up-server.herokuapp.com/api/v1/oauth/google
  2. 这会通过他们的网站启动 Google 登录过程
  3. 登录成功 + 数据已插入 MySQL 数据库
  4. 然后应用被带到错误页面

似乎无法调用回调 URL,它应该是: https://gym-up-server.herokuapp.com/api/v1/oauth/google/callback

我正在使用以下依赖项:Express、MySQL、Sequelize、Passport

这是我的代码:

路线:

// =====================================
// GOOGLE ROUTES =======================
// =====================================
// send to google to do the authentication
// profile gets us their basic information including their name
// email gets their emails
router.get(
  "/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

// the callback after google has authenticated the user
router.get("/google/callback", passport.authenticate("google"), 
function(req,res) {
  res.render("index");
  console.log("After Passport AUTH");
});

护照 JS

// =========================================================================    


// GOOGLE ==================================================================
  // =========================================================================
  passport.use(
    new GoogleStrategy(
      {
        clientID: configAuth.googleAuth.clientID,
        clientSecret: configAuth.googleAuth.clientSecret,
        callbackURL: configAuth.googleAuth.callbackURL
      },
      function(token, refreshToken, profile, done) {
        console.log("getting data from Google");
        // make the code asynchronous
        // User.findOne won't fire until we have all our data back from Google
        process.nextTick(function() {
          // try to find the user based on their google id
          console.log("profile ID :", profile.id);
          models.User.findOne({ where: { ggId: profile.id } }).then(function(
            user
          ) {
            // if (err) return done(err);
            if (user) {
              // if a user is found, log them in
              return done(null, user);
            } else {
              // if the user isnt in our database, create a new user
              var data = {
                // set all of the relevant information
                ggId: profile.id,
                ggToken: token,
                ggName: profile.displayName,
                ggEmail: profile.emails[0].value // pull the first email
              };
              //save user
              models.User.create(data, {
                fields: ["ggId", "ggToken", "ggName", "ggEmail"]
              }).then(function(insertedUser) {
                console.log(
                  "User Created!" + ": " + insertedUser.get({ plain: true })
                );
                // console.log("about to run DONE to go back to ROUTE");
                // return done(null, insertedUser.get({ plain: true }));
                if (!insertedUser) {
                  console.log("failed to insert user - nothing found!");
                  return done(null, false);
                }
                if (insertedUser) {
                  console.log("about to run DONE to go back to ROUTE");
                  return done(null, insertedUser);
                }
              });
            }
          });
        });
      }
    )
  );

【问题讨论】:

    标签: javascript mysql node.js oauth sequelize.js


    【解决方案1】:

    您需要将回调 url 传递给 google 在回调路由中进行身份验证。您提到的教程有 successRedirect 和 failureRedirect 路由。

    例如:添加成功和失败路由如下。

    // route for success
    app.get('/', function(req, res) {
        res.render('index.ejs'); // load the index.ejs file
    });
    
    
     // route for failure
    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user : req.user // get the user out of session and pass to template
        });
    });
    

    然后将通过成功和失败的路由添加到 google 身份验证

    app.get('/auth/google/callback',
            passport.authenticate('google', {
                    successRedirect : '/profile',
                    failureRedirect : '/'
            }));
    

    【讨论】:

    • 我添加了您建议的两条路线,但它似乎仍然不起作用。我还测试了两条路线以确保它们也能渲染。一切似乎都对 find 进行了身份验证,但是当它返回到我的应用程序时,它只是错误。还有其他建议吗?
    • 我看到的只是:500 (Internal Server Error) - 它似乎不会导致任何其他错误。当我运行代码时,它会执行护照 JS 代码并到达 return done(null, insertedUser); 部分,因为我看到打印了 console.log("about to run DONE to go back to ROUTE");,我认为这意味着它正在返回路由,然后它应该运行 successRedirect 是吗?所以我不确定它为什么不渲染。
    【解决方案2】:

    我找到了解决方案。但我不完全确定它为什么会起作用。

    // the callback after google has authenticated the user
    router.get("/google/callback", function(req, res, next) {
      passport.authenticate("google", function(err, user, info) {
        res.redirect("/profile");
      })(req, res, next);
    });
    

    希望这对其他人有所帮助。花了很长时间才弄明白这个!

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2020-08-18
      • 1970-01-01
      • 2012-10-04
      相关资源
      最近更新 更多