google-auth-library错误:invalid_request缺少必需的参数:response_type

时间:2020-04-07 23:00:23

标签: oauth-2.0 google-oauth google-authentication

我正在尝试通过Google-Auth-Library以编程方式获取Google访问令牌。我已经有一个client_id,client_secret和刷新令牌。我确实从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

0 个答案:

没有答案
相关问题