javascript - 如何使用 Passport.js 将数据从 React 客户端传递到 Oauth2.0 Google 策略流程

标签 javascript node.js reactjs oauth-2.0 passport.js

我想在我的 React 客户端获取用户提供的用户名,并在身份验证流程中将其传递到我的服务器端的 Google Oauth。我原本以为我可以通过简单地调用/api/auth/google/${username} 并使用 req.update() 将其保存到我的 mongo 数据库或将其附加到 google 返回的配置文件对象来将其与 req.params.username 一起传递通过 profile.username = req.params.username。不幸的是,我不太熟悉谷歌策略作为中间件的运作方式。

目前,用户通过发送到/api/auth/google 进行注册,然后 Google 策略会自动处理流程。

    app.get('/auth/google', passport.authenticate('google', {
        scope: ['profile', 'email']
      }))

我的 Google 策略如下:

    passport.use(new GoogleStrategy(
      {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: "/auth/google/callback",
      proxy: true
    }, 
    async (accessToken, refreshToken, profile, done) => {
      const existingUser = await User.findOne({ googleId: profile.id, 
    image: profile.photos[0].value})

      if (existingUser){
        return done(null, existingUser);
      } 

      const newUser = new User({ googleId: profile.id, image: 
    profile.photos[0].value}).save();  
      done(null, newUser);    
      })
    );

以及回调路由:

    app.get('/auth/google/callback', passport.authenticate('google'), 
       (req, res) => {
         res.redirect('/')
       })

由于返回的用户配置文件保存到 Google 策略本身内的 mongo 数据库中,因此我不确定如何将 req.params.username 附加到配置文件对象。关于在执行 newUser = ().save() 命令之前如何访问 Google 策略中的用户名有什么建议吗?或者是否有更好的方法将用户名附加到已保存的用户?

最佳答案

你最初的想法是正确的;您只是缺少一个实现细节。 OAuth2 策略(例如您在此处使用的 GoogleStrategy)可以在策略配置选项中传递 {passReqToCallback: true} 标志。设置后,您的回调将有权访问原始请求:

passport.use(new GoogleStrategy({
  clientID: keys.googleClientID,
  clientSecret: keys.googleClientSecret,
  callbackURL: "/auth/google/callback",
  proxy: true,
  passReqToCallback: true
}, 
async (req, accessToken, refreshToken, profile, done) => {
  // Now you have access to the original req.params.username, or any data
  // the original request has attached to it
  ...
})

另请参阅:

Using PassportJS, how does one pass additional form fields to the local authentication strategy?

Get request object in Passport strategy callback

关于javascript - 如何使用 Passport.js 将数据从 React 客户端传递到 Oauth2.0 Google 策略流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51758440/

相关文章:

javascript - 使用 JQuery 自动录制并允许播放一次

node.js - 从 Linux 上的 NodeJS 打印到 Star TSP143LAN,带格式

node.js - 如何从 socket.io 中访问 req.session 变量?

javascript - 如何向按钮添加多个事件监听器?

javascript - Internet Explorer 7 中的 HTML 5 session 存储

javascript - 如何删除 LokiJS 中的集合

javascript - 展平子数组的对象

javascript - Spread 运算符不再传入 React Native map 函数

javascript - csrfToken 仅在页面刷新后有效 - Django

javascript - 在浏览器中检查 session 过期