google-auth-library Ошибка: invalid_request Отсутствует обязательный параметр: тип ответа - PullRequest
0 голосов
/ 08 апреля 2020

Я пытаюсь программно получить токен доступа Google через Google-Auth-Library. У меня уже есть токен client_id, client_secret и refre sh. Я буквально скопировал код из документации Google 1 , но получаю Error: invalid_request Required parameter is missing: response_type

Я пытался добавить response_type: 'code' во многих местах кода, но я получаю те же ответы ... Куда я должен добавить этот параметр?

const {OAuth2Client} = require('google-auth-library');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');

const keys = require('./oauth2.keys.json');

async function main() {
  try {
    const oAuth2Client = await getAuthenticatedClient();
    const url = 'https://accounts.google.com/o/oauth2/v2/auth';
    const res = await oAuth2Client.request({url});
    console.log(res.data);

    const tokenInfo = await oAuth2Client.getTokenInfo(
      oAuth2Client.credentials.access_token
    );
    console.log(tokenInfo);
  }
  catch (err) {
    console.log(`oauth2: ${err}`);
  }
}

function getAuthenticatedClient() {
  return new Promise((resolve, reject) => {
    const oAuth2Client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/youtube',
    });

    const server = http
    .createServer(async (req, res) => {
      try {
        if (req.url.indexOf('/oauth2callback') > -1) {
          // acquire the code from the querystring, and close the web server.
          const qs = new url.URL(req.url, 'http://localhost:3000')
            .searchParams;
          const code = qs.get('code');
          console.log(`Code is ${code}`);
          res.end('Authentication successful! Please return to the console.');
          server.destroy();

          const r = await oAuth2Client.getToken(code);
          // Make sure to set the credentials on the OAuth2 client.
          oAuth2Client.setCredentials(r.tokens);
          console.info('Tokens acquired.');
          resolve(oAuth2Client);
        }
      } catch (e) {
        reject(e);
      }
    })
    .listen(3000, () => {
      // open the browser to the authorize url to start the workflow
      open(authorizeUrl, {wait: false}).then(cp => cp.unref());
    });
    destroyer(server);
  });
}

main();

Обратите внимание, что URL (oauth2) и URL области (область YouTube) были изменены для целей моего проекта по сравнению с документацией.

[1] https://github.com/googleapis/google-auth-library-nodejs

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...