Google-API-nodeJS-客户端在使用令牌交换代码时抛出invalid_request错误



我有一个简单的客户端应用程序,使用具有此设置的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' }

如果我将重定向URL添加到开发人员控制台,客户端应用程序和服务器端应用程序,则会收到redirect_uri_mismatch错误。

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

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

找到解决方案

根据这篇文章中的一个回复(令人惊讶的是,不是答案(,

我需要做的就是在我的客户端 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个小时的工作,搜索和敲打我的头到桌子上。我想知道为什么谷歌开发者网站上没有明确的文档。或者也许有,我找不到它们。

相关内容

最新更新