我们正在使用Vue和vue-google-oauth2在前端进行OAuth握手,如下所示:
async handleGoogleLogin() {
try {
const googleUser = await this.$gAuth.signIn();
const idToken = googleUser.getAuthResponse().id_token;
const response = await axios.post('http://localhost:3000/api/auth/google', {
provider: 'google',
clientId: this.$googleAuthClientId,
idToken: `${idToken}`,
});
console.log('jwt: ', response);
// TODO get and store the token
this.$router.push('/');
} catch (error) {
console.log('error is', error);
}
},
然后在服务器端,我们使用“ passport-google-oauth20”设置了Passport。这个问题是我不确定如何让护照接受来自前端的id_token,而不进行整个重定向舞蹈?
目前,我们通过实现Passport(代码使用Typescript)解决了Passport:
async googleVerify(token: string, clientId: string) {
const googleOAuth2Client = new OAuth2Client(clientId);
const ticket = await googleOAuth2Client.verifyIdToken({
idToken: token,
audience: clientId,
});
return ticket.getPayload();
}
async authenticateGoogle (req: Request, res: Response, next: NextFunction) {
const token = req.body.idToken;
const clientId = req.body.clientId;
try {
console.log('.....', token, clientId);
const result = await this.googleVerify(token, clientId);
// TODO create user if not existing
// return JWT
res.json(result);
} catch (error) {
next(error);
}
};