1

我正在尝试添加 Google 身份验证,但遇到了一个问题:

我正在使用这个回购代码:https ://github.com/conorbailey90/Google-Auth

这里我有前端代码。这只是向id_token服务器发送一个带有 json 格式的 post 请求而已:

function onSignIn(googleUser) {
    var id_token = googleUser.getAuthResponse().id_token; // get the id_token and send it to server
    // send the id_token to server using a simple post request
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/google-login');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function() {
        // console.log('Signed in as: ' + xhr.responseText);
        if(xhr.responseText == 'success'){
            signOut();
            // location.assign('/profile')
        }
    };
    xhr.send(JSON.stringify({token : id_token}));
}

在我的 server.js 中:(注意我向你展示了我CLIENT_ID是否想在你身边测试这个)

const {OAuth2Client} = require('google-auth-library');
const CLIENT_ID = '203772907695-qd52ou2r1bcsht8f515lh63cpqaateq2.apps.googleusercontent.com'
const client = new OAuth2Client(CLIENT_ID);

app.post('/google-login',async (req, res) => {

    let token = req.body.token;

    console.log('token', token); // I get the token which is sent from front-end successfully

    // I can successfully get the data from a simple post request to this endpoint so I'm sure there is nothing wrong with the token and its valid

    const resp = await axios.post(`https://oauth2.googleapis.com/tokeninfo?id_token=${token}`);

    console.log('res', resp)

    async function verify() {
        // the verifyIdToken function below causes the error
        const ticket = await client.verifyIdToken({
            idToken: token,
            audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
        });
        // because the above error I never reach here
        const payload = ticket.getPayload();
        const userid = payload['sub'];
    }

    verify()
        .then((e)=> {
            res.send('success')
        })
        .catch(err => console.log(err));

})

如您所见,该verifyIdToken函数会导致以下错误,而我确信令牌 100% 有效:

GaxiosError: Failed to retrieve verification certificates: <!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 403 (Forbidden)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>403.</b> <ins>That’s an error.</ins>
  <p>Your client does not have permission to get URL <code>/oauth2/v1/certs</code> from this server.  <ins>That’s all we know.</ins>

    at Gaxios._request (C:\inetpub\wwwroot\Server\node_modules\gaxios\build\src\gaxios.js:129:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async OAuth2Client.getFederatedSignonCertsAsync (C:\inetpub\wwwroot\Server\node_modules\google-auth-library\build\src\auth\oauth2client.js:454:19)
    at async OAuth2Client.verifyIdTokenAsync (C:\inetpub\wwwroot\Server\node_modules\google-auth-library\build\src\auth\oauth2client.js:395:26)
    at async verify (C:\inetpub\wwwroot\Server\server.js:161:22) {
  response: {
    config: {
      url: 'https://www.googleapis.com/oauth2/v1/certs',
      headers: [Object],
      paramsSerializer: [Function: paramsSerializer],
      validateStatus: [Function: validateStatus],
      responseType: 'json',
      method: 'GET'
    },
    data: '<!DOCTYPE html>\n' +
      '<html lang=en>\n' +
      '  <meta charset=utf-8>\n' +
      '  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n' +
      '  <title>Error 403 (Forbidden)!!1</title>\n' +
      '  <style>\n' +
      '    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}\n' +
      '  </style>\n' +
      '  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\n' +
      '  <p><b>403.</b> <ins>That’s an error.</ins>\n' +
      '  <p>Your client does not have permission to get URL <code>/oauth2/v1/certs</code> from this server.  <ins>That’s all we know.</ins>\n',
    headers: {
      'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
      connection: 'close',
      'content-length': '1594',
      'content-type': 'text/html; charset=UTF-8',
      date: 'Fri, 23 Jul 2021 14:45:00 GMT',
      'referrer-policy': 'no-referrer'
    },
    status: 403,
    statusText: 'Forbidden',
    request: { responseURL: 'https://www.googleapis.com/oauth2/v1/certs' }
  },
  config: {
    url: 'https://www.googleapis.com/oauth2/v1/certs',
    headers: {
      'User-Agent': 'google-api-nodejs-client/7.3.0',
      'x-goog-api-client': 'gl-node/16.2.0 auth/7.3.0',
      Accept: 'application/json'
    },
    paramsSerializer: [Function: paramsSerializer],
    validateStatus: [Function: validateStatus],
    responseType: 'json',
    method: 'GET'
  },
  code: '403'
}

错误中的第一句话是:

GaxiosError:检索验证证书失败:

我们看到这个错误有点低:

您的客户端无权 /oauth2/v1/certs从此服务器获取 URL。我们知道的就这些。

这是我的谷歌控制台配置(也许我在这里有错误):

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

4

0 回答 0