【问题标题】:google-api-nodejs-client throws invalid_request error when exchanging code with tokensgoogle-api-nodejs-client 在使用令牌交换代码时抛出 invalid_request 错误
【发布时间】:2018-06-15 23:52:25
【问题描述】:

我有一个使用 react-google-login 的简单客户端应用程序:

<GoogleLogin
        clientId={config.CLIENT_ID}
        scope={config.SCOPES.join(' ')}
        buttonText="Login With Google"
        onSuccess={response => onSignIn('google', response)}
        onFailure={this.failure.bind(this)}
        accessType="offline"
        responseType="code"
      />

它成功检索代码并将其发送到用NodeJS编写的后端服务器。

服务器端代码如下所示:

const { google } = require('googleapis');
const config = global.config;
const oauth2Client = new google.auth.OAuth2({
  clientId: config.google.CLIENT_ID,
  clientSecret: config.google.CLIENT_SECRET,
});

// code omitted for the sake of simplicity

var authCode = req.body.authCode; // the provided code by google

const { tokens } = await oauth2Client.getToken(authCode);
return tokens;

当我运行代码时,它会抛出错误:

{ error: 'invalid_request',
        error_description: 'Missing parameter: redirect_uri' } },
  code: '400' }

如果我将redirectUrl 添加到开发者控制台、客户端应用程序和服务器端应用程序,我将收到redirect_uri_mismatch 错误。

我有点卡在这里,在网上找不到任何有用的东西。

任何解决方法将不胜感激。

【问题讨论】:

  • 您必须在您的 Google 应用中设置相同的 redirect_uri 服务器端。
  • 我做到了。我收到了redirect_uri_mismatch 错误。
  • 您收到不匹配错误,因为您在应用中保存的 URL 与您在请求中发送的 URL 不同。 URL 必须完全相同。
  • 谢谢@marekful,但我找到了解决方案并在下面分享。问题根本不是网址。我不得不使用postmessage 而不是 url

标签: node.js google-oauth google-api-nodejs-client


【解决方案1】:

找到解决方案

基于this post 上的其中一个回复(令人惊讶的是,不是答案),

我需要做的就是在我的客户端 react-google-login 按钮和服务器上的 oauth2Client 配置中输入 postmessage 而不是实际 URL。

根本不需要开发者控制台上的redirect_uri。

<GoogleLogin
            clientId={config.CLIENT_ID}
            ****redirectUri="postmessage"****
            scope={config.SCOPES.join(' ')}
            buttonText="Login With Google"
            onSuccess={response => onSignIn('google', response)}
            onFailure={this.failure.bind(this)}
            accessType="offline"
            responseType="code"
          />

const oauth2Client = new google.auth.OAuth2({
  clientId: config.google.CLIENT_ID,
  clientSecret: config.google.CLIENT_SECRET,
  ****redirectUri: 'postmessage'****
});

确实解决了问题。 5个小时的工作,搜索和敲打我的头到桌子上。我想知道为什么 Google Developers 网站上没有明确的文档。或者可能有,但我找不到。

【讨论】:

  • 这个解决方案对我帮助很大。指南中仍然没有关于“postmessage”的内容
  • 你让我免于发疯!
猜你喜欢
  • 2016-08-04
  • 2013-02-06
  • 1970-01-01
  • 2012-09-16
  • 2017-06-18
  • 1970-01-01
  • 2012-03-26
  • 2015-05-31
  • 2017-08-07
相关资源
最近更新 更多