我想在React客户端获取用户提供的用户名,并在身份验证过程中将其传递到服务器端的Google Oauth中。我最初认为可以通过调用/api/auth/ google /${username}将其传递给req.params.username,然后使用req.update()将其保存到我的mongo数据库中,或者通过profile.username = req.params.username将其附加到google返回的配置文件对象。不幸的是,我对Google策略是如何作为中间件工作的还不够熟悉。
目前,用户通过被发送到/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 db中,因此我不确定如何将req.params.username附加到配置文件对象。在我执行newUser = ().save()命令之前,对如何访问谷歌策略中的用户名有什么建议吗?或者,有没有更好的方法将用户名附加到保存的用户?
发布于 2018-08-12 05:52:33
您最初的想法恰到好处;您只是遗漏了一个实现细节。可以在策略配置选项中向OAuth2策略传递一个{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?
https://stackoverflow.com/questions/51758440
复制相似问题