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

Dus*_*tin 5 javascript node.js express passport.js

因此,我正在研究此处提供的信息,以增加Google重定向到用户所在页面的能力,然后再重定向到google。我目前正在使用Express,PassportJS和Google oauth2的最新版本。

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

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

我本质上希望我的功能看起来像这样,但是我无法访问req.header,或者只是不知道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) {});
Run Code Online (Sandbox Code Playgroud)

lag*_*lex 6

制作自定义中间件

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

改为将其添加到您的路线

app.get("/auth/google", myCustomGoogleAuthenticator, function(req, res) {});
Run Code Online (Sandbox Code Playgroud)