使用Node js验证Google ID令牌

时间:2019-11-01 22:44:10

标签: javascript node.js swift

我有一个iOS应用,正在将Google ID发送到后端服务器进行验证。

我遵守Google准则:https://developers.google.com/identity/sign-in/web/backend-auth

我对Node js还是很陌生,我无法弄清为什么从来不执行回调函数(即,promise无法解析或拒绝):

const verifyToken = new Promise(function(resolve, reject){
    console.log("promise function")
    client.verifyIdToken({
        idToken: token,
        audience: process.env.CLIENT_ID, 
        function (e, login){
            console.log(e)
           if (login) {
               var payload = login.getPayload();
               var googleId = payload['sub'];
               resolve(googleId);
            } else {
            reject("invalid token");
           }
        }
    });
});
verifyToken.then((token) => {
    console.log("RESOLVED");
    jwt.sign({id: googleId}, 'secret key', { algorithm: 'RS256' }, (err, token) => {
        console.log("sending data back");
        res.send(token);
    });
});
verifyToken.catch((message) => {
    console.log("REJECTED");
    res.send(message);
});

2 个答案:

答案 0 :(得分:2)

创建新的Promise后,它将自动执行。您在执行程序中传递的resolve和reject函数将在被调用时分别将Promise的状态更改为resolve或被拒绝。看看this link

.then和.catch实现将针对已解决和被拒绝的诺言执行。因此,就承诺的执行而言,您的代码看起来不错。

取决于控件是否即将到达您编写的块。正如我在您的实现中看到的 res.send 一样,它必须位于某些(req,res)中间件中。

所以检查执行是否正在该中间件上。

答案 1 :(得分:1)

验证Google ID令牌的最佳方法是使用下面 npm 中的 google-auth-library 是用于验证从客户端发送到服务器的tokenId的示例代码片段,希望对您有所帮助。

const {GOOGLE_CLIENT_ID, JWT_SECRET } = process.env;

app.post('/api/v1/auth/google', async ({ body: { tokenId } }, res) => {

  const client = new OAuth2Client(GOOGLE_CLIENT_ID);

  const ticket = await client.verifyIdToken({
    idToken: tokenId,
    audience: GOOGLE_CLIENT_ID,
  });

  const response = ticket.getPayload();

  if (response.iss !== 'accounts.google.com' && response.aud !== GOOGLE_CLIENT_ID)
    return res.status(400).json({ status: 'error', error: 'Bad Request' });

  const user = {
    email: response.email,
    image: response.picture,
    social_id: response.sub,
    first_name: response.given_name,
    last_name: response.family_name,
  };

  let result = await User.findOne({
    where: { [Op.or]: [{ email: user.email }, { social_id: user.social_id }] },
  });

  if (!result) result = await User.create(user);

  const token = await jwt.sign({ id: result.dataValues.id }, JWT_SECRET, { expiresIn: '1hr' });
  const data = { token, ...result.dataValues};

  res.status(200).json({ status: 'success', data });

});