PassportJS - 动态设置状态以允许在回调时重定向

PassportJS - Dynamically set state to allow redirect on callback

本文关键字:回调 重定向 动态 设置 状态 PassportJS      更新时间:2023-09-26

所以我正在处理这里提供的信息,以添加Google在重定向到Google之前将重定向到用户所在的页面的功能。我目前正在使用最新版本的Express,PassportJS和Google oauth2。

例如,如果用户点击页面 http://example.com/privatecontent,它会自动重定向到 Google 要求登录,成功后它会返回到我的 Node App,只是它不知道最后一页是/privatecontent,而是重定向到索引。

如果我理解正确,我可以使用 state 参数让 Google 知道将状态参数发回,以便我可以读取它并重定向自己。

我基本上希望我的函数看起来像这样,但我无法访问 req.headers,或者只是不知道在 passport.authenticate 中有多诚实。

app.get("/auth/google", passport.authenticate("google", {
  scope: ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
  state: base64url(JSON.stringify({
    lastUrl: req.headers['referer']
  }))
}), function(req, res) {});

创建自定义中间件

function myCustomGoogleAuthenticator(req, res, next){
    passport.authenticate({
        scope: ...
        state: // now you have `req`
    })(req, res, next);
    //^ call the middleware returned by passport.authenticate
}

改为将其添加到您的路线中

app.get("/auth/google", myCustomGoogleAuthenticator, function(req, res) {});