首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >"invalid_grant“/”坏请求“同时为编写代码google获取令牌

"invalid_grant“/”坏请求“同时为编写代码google获取令牌
EN

Stack Overflow用户
提问于 2021-12-13 13:56:24
回答 2查看 3.2K关注 0票数 1

我正在尝试将google日历集成到我的应用程序中,但是得到了一个错误:‘无效_授予’,error_description:‘坏请求’

我也一直在跟踪谷歌的文档,并参考了相关的StackOverflow帖子来解决这个问题,但到目前为止还没有什么好结果。我正在实现的流程如下:

  1. 生成google同意书url const {client_secret,client_id,redirect_uris} = credentials.web;const oAuth2Client =新google.auth.OAuth2( client_id,client_secret,redirect_uris );const authUrl = oAuth2Client.generateAuthUrl({ access_type:‘脱机’,作用域:作用域,提示:‘同意’};console.log(‘通过访问此url:',authUrl来授权此应用程序);
  2. 在用户同意后,从URL中提取auth代码并尝试获取令牌以交换authcode const { client_secret,client_id,redirect_uris }= credentials.web;const OAuthtoClient =新google.auth.OAuth2( client_id,client_secret,redirect_uris );让解码=decodeURIComponent(代码);OAuthtoClient.getToken(解码,(错误,令牌) => { if (错误)返回console.error(“错误检索访问令牌”,err);console.log(此处令牌:',令牌);

首先,我得到了另一个错误{ " error ":"invalid_grant","error_description":“畸形的auth代码。”},这是针对这个解决方案解决的。代码运行了一次,我第一次能够生成"refresh_token和access_token“。

在尝试为另一个用户生成令牌之后,我得到了以下错误错误:“无效_授予”,error_description:“坏请求”

我尝试过重置客户端机密之类的东西,但没有任何进展。

我的重定向网址是"redirect_uris": [ "https://example.com/authenticate-gcalendar", "http://localhost:3000" ]

原点URL "javascript_origins": [ "http://localhost:4000" ]

范围const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.events'];

提前谢谢你!

以下是完全错误消息

代码语言:javascript
运行
复制
Error retrieving access token GaxiosError: invalid_grant
at Gaxios.<anonymous> (F:\Git Clones\user-module\node_modules\gaxios\build\src\gaxios.js:73:27)
at Generator.next (<anonymous>)
at fulfilled (F:\Git Clones\user-module\node_modules\gaxios\build\src\gaxios.js:16:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
response: {
config: {
  method: 'POST',
  url: 'https://oauth2.googleapis.com/token',
  data: 'code=4%2F0AX4XfWiJdQtBAPFLwGHm6O5fotnjqYqHUSYzgUhvFpYyeQ7CziXcd_rc1f5bKMYJaJpklg&client_id&client_secret&redirect_uri=https%3A%2F%2Fexample.com%2Fauthenticate-gcalendar&grant_type=authorization_code&code_verifier=',
  headers: [Object],
  params: [Object: null prototype] {},
  paramsSerializer: [Function: paramsSerializer],
  body: 'code=4%2F0AX4XfWiJdQtBAPFLwGHm6O5fotnjqYqHUSYzgUhvFpYyeQ7CziXcd_rc1f5bKMYJaJpklg&client_id&client_secret&redirect_uri=https%3A%2F%2Fexample.com%2Fauthenticate-gcalendar&grant_type=authorization_code&code_verifier=',
  validateStatus: [Function: validateStatus],
  responseType: 'json'
},
data: { error: 'invalid_grant', error_description: 'Bad Request' },
headers: {
  'alt-svc': 'h3=":443"; ma=2592000,h3-29=":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"',
  'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
  connection: 'close',
  'content-encoding': 'gzip',
  'content-type': 'application/json; charset=utf-8',
  date: 'Mon, 13 Dec 2021 13:01:12 GMT',
  expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
  pragma: 'no-cache',
  server: 'scaffolding on HTTPServer2',
  'transfer-encoding': 'chunked',
  vary: 'Origin, X-Origin, Referer',
  'x-content-type-options': 'nosniff',
  'x-frame-options': 'SAMEORIGIN',
  'x-xss-protection': '0'
   },
status: 400,
statusText: 'Bad Request'
},
 config: {
method: 'POST',
url: 'https://oauth2.googleapis.com/token',
data: 'code=4%2F0AX4XfWiJdQtBAPFLwGHm6O5fotnjqYqHUSYzgUhvFpYyeQ7CziXcd_rc1f5bKMYJaJpklg&client_id&client_secret&redirect_uri=https%3A%2F%2Fexample.com%2Fauthenticate-gcalendar&grant_type=authorization_code&code_verifier=',
headers: {
  'Content-Type': 'application/x-www-form-urlencoded',
  'User-Agent': 'google-api-nodejs-client/3.1.2',
  Accept: 'application/json'
},
params: [Object: null prototype] {},
paramsSerializer: [Function: paramsSerializer],
body: 'code=4%2F0AX4XfWiJdQtBAPFLwGHm6O5fotnjqYqHUSYzgUhvFpYyeQ7CziXcd_rc1f5bKMYJaJpklg&client_id&client_secret&redirect_uri=https%3A%2F%2Fexample.com%2Fauthenticate-gcalendar&grant_type=authorization_code&code_verifier=',
validateStatus: [Function: validateStatus],
responseType: 'json'
},
code: '400'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-27 16:53:44

我解决了我的问题

我遵循google文档并在其上构建我的代码,所有代码都是正确的,但仍然是"invalid_grant“。

在我的例子中,我将google重定向到我的应用程序的url,同时运行到我的本地主机。将其重定向到http://127.0.0.1:4000后,错误得到了解决。

票数 2
EN

Stack Overflow用户

发布于 2021-12-13 14:32:31

无效的授予可能是一个很难诊断的错误。您应该从遵循正式的Node.js快速启动开始

代码语言:javascript
运行
复制
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Calendar API.
  authorize(JSON.parse(content), listEvents);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the next 10 events on the user's primary calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {
  const calendar = google.calendar({version: 'v3', auth});
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = res.data.items;
    if (events.length) {
      console.log('Upcoming 10 events:');
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
      });
    } else {
      console.log('No upcoming events found.');
    }
  });
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70335826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档