首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用passport.js将数据从React客户端传递到Oauth2.0Google策略流程

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

Stack Overflow用户
提问于 2018-08-09 11:36:41
回答 1查看 693关注 0票数 2

我想在React客户端获取用户提供的用户名,并在身份验证过程中将其传递到服务器端的Google Oauth中。我最初认为可以通过调用/api/auth/ google /${username}将其传递给req.params.username,然后使用req.update()将其保存到我的mongo数据库中,或者通过profile.username = req.params.username将其附加到google返回的配置文件对象。不幸的是,我对Google策略是如何作为中间件工作的还不够熟悉。

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

代码语言:javascript
复制
    app.get('/auth/google', passport.authenticate('google', {
        scope: ['profile', 'email']
      }))

我的Google策略如下:

代码语言:javascript
复制
    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);    
      })
    );

以及回调路由:

代码语言:javascript
复制
    app.get('/auth/google/callback', passport.authenticate('google'), 
       (req, res) => {
         res.redirect('/')
       })

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-12 05:52:33

您最初的想法恰到好处;您只是遗漏了一个实现细节。可以在策略配置选项中向OAuth2策略传递一个{passReqToCallback: true}标志。设置完成后,您的回调将可以访问原始请求:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51758440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档