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