简体   繁体   English

使用 Node js 验证 Google ID 令牌

[英]Verify Google ID Token with Node js

I have an iOS app that's sending a google id to a backend server for validation.我有一个 iOS 应用程序,该应用程序将 google id 发送到后端服务器进行验证。

I'm following the Google guidelines:https://developers.google.com/identity/sign-in/web/backend-auth我遵循谷歌指南:https://developers.google.com/identity/sign-in/web/backend-auth

I'm quite new to Node js and I can't figure out why the callback function never gets executed (ie, the promise doesn't resolve nor reject):我对 Node js 很陌生,我不知道为什么回调 function 永远不会被执行(即 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);
});

When a new Promise is created it will execute automatically.创建新的 Promise 时,它将自动执行。 The resolve and reject functions you passed in the executor will change the state of promise to resolved or rejected respectively when called.您在执行程序中传递的解析和拒绝函数将在调用时将 promise 的 state 分别更改为已解决或拒绝。 Have a look at this link看看这个链接

The.then and.catch implementations will execute for the resolved and rejected promise. .then 和.catch 实现将针对已解决和拒绝的 promise 执行。 So your code looks fine as far as execution of promise is concerned.因此,就 promise 的执行而言,您的代码看起来不错。

Depends if the control is coming to the block you've written.取决于控件是否到达您编写的块。 As i can see res.send in your implementation it must be inside some (req,res) middleware.正如我在你的实现中看到的res.send它必须在一些 (req,res) 中间件中。

So check if the execution is coming to the that middleware.因此,请检查执行是否到达该中间件。

The best way to verify Google ID token is to use google-auth-library from npm below is a sample snippet for validating the tokenId sent from client to the server, hope it helps.验证 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 });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM