我目前在处理连接到我自己的节点Express api服务器的vue应用中无法处理google oAuth登录。
在express api服务器上,我使用护照作为中间件来处理google oauth,通过google成功登录后,我在后端的回调中生成了jwt。
passport.use(new GoogleStrategy({
clientID: config.get('google.clientID'),
clientSecret: config.get('google.clientSecret'),
callbackURL: config.get('google.callbackUrl'),
},
function(accessToken, refreshToken, profile, done) {
User.findOne(
{ socialID: profile.id },
function (err, user) {
if (err) {
return done(err);
}
//No user was found... so create a new user with values from Facebook (all the profile. stuff)
if (!user) {
user = new User({
name: profile.displayName,
email: profile.emails[0].value,
provider: profile.provider,
socialID: profile.id,
});
user.save(function(err) {
if (err) console.log(err);
});
}
// the information which shall be inside the jsonwebtoken
const payload = {
user: {
id: user.id
}
};
// create jsonwebtoken and return it
jwt.sign(
payload,
config.get('jwt.secret'), // get the secret from default.json to hash jsonwebtoken
{ expiresIn: config.get('jwt.lifetime') },
(err, token) => {
if(err) throw err; // if there is error, throw it and exit
return done(JSON.stringify(token)); // return jwt token
}
);
}
);
}
));
我的api服务器上有这些路由
// @route GET api/auth/google
// @desc Google auth route - get User From Google, store it if not exists yet
// @access Public
router.get('/google',
passport.authenticate('google', { scope: ['profile', 'email'], session: false })
);
// @route GET api/auth/google/callback
// @desc Google callback route
// @access Public
router.get('/google/callback',
passport.authenticate('google', { failureRedirect: '/', session: false }),
function (req, res) {
res.redirect('http://localhost:8080/?token=' + res);
}
);
当我在/ auth / google调用我的后端api路由时,我成功地重定向到了Google登录页面。但是,使用我的方法,我试图使用get参数“ token”从回调URL重定向回我的vue应用,以在前端接收令牌。我的后端回调路由中的重定向不起作用。如何将后端生成的令牌传递给前端?
我发现重定向无法正常工作,因为return done()函数期望两个参数可以正常工作。
我在Google护照中间件中更改了完成的功能,如下所示
jwt.sign(
payload,
config.get('jwt.secret'), // get the secret from default.json to hash jsonwebtoken
{ expiresIn: config.get('jwt.lifetime') },
(err, token) => {
if(err) throw err; // if there is error, throw it and exit
return done(null, token); // return jwt token
}
);
现在,在我的路由内,我可以成功地重定向+将令牌添加为get参数-因此,通过这种解决方法,我可以在前端接收到我在后端生成的jwt。
// @route GET api/auth/google/callback
// @desc Google callback route
// @access Public
router.get('/google/callback',
passport.authenticate('google', { failureRedirect: '/', session: false }),
function (req, res) {
let token = res.req.user;
res.redirect('//localhost:8080/?token=' + token);
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句