错误:提供的密钥文件未定义有效的重定向URI

时间:2019-10-06 13:33:09

标签: node.js api youtube server-side

尝试使用Youtube Data API制作一些小型项目 现在尝试通过git中的示例上传代码将视频上传到youtube。 我已经设置了Google Oauth2的凭据,这是我得到的JSON:

{"web":{"client_id":***,
"project_id":***,
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":***,
"redirect_uris":["http://localhost:5000/oauth2callback"],
"javascript_origins":["http://localhost:5000"]}}

我在的时候。尝试上传视频时,我不断遇到以下错误:

错误:提供的密钥文件未定义有效的 重定向URI。必须至少定义一个重定向URI,并且此示例 假设它重定向到“ http://localhost:3000/oauth2callback”。请编辑 您的密钥文件,并添加“ redirect_uris”部分。例如:

"redirect_uris": [
  "http://localhost:3000/oauth2callback"
]

我是node.js的初学者,很难弄清是什么。为了使其工作所需。 我很高兴获得一些答案,这将帮助我重回正轨。

1 个答案:

答案 0 :(得分:0)

我有同样的问题。在我看来,他们的示例文件sampleClient.js在寻找redirect_uris正常工作的方式上有错误。

请在下面的工作示例中找到,希望对您有所帮助:

// Copyright 2016 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict'

const port = 3002

/**
 * This is used by several samples to easily provide an oauth2 workflow.
 */

// [START auth_oauth2_workflow]
const { google } = require('googleapis')
const http = require('http')
const url = require('url')
const opn = require('open')
const destroyer = require('server-destroy')
const fs = require('fs')
const path = require('path')

const keyPath = path.join(__dirname, 'oauth2.keys.json')
// let keys = {
//   redirect_uris: [`http://localhost:${port}/oauth2callback`]
// }

// if (fs.existsSync(keyPath)) {
//   const keyFile = require(keyPath)
//   console.log(keyFile)
//   keys = keyFile.installed || keyFile.web
// }

const keyFile = require(keyPath)

const invalidRedirectUri = `The provided keyfile does not define a valid
redirect URI. There must be at least one redirect URI defined, and this sample
assumes it redirects to 'http://localhost:${port}/oauth2callback'.  Please edit
your keyfile, and add a 'redirect_uris' section.  For example:
"redirect_uris": [
  "http://localhost:3002/oauth2callback"
]
`

class SampleClient {
  constructor(options) {
    this._options = options || { scopes: [] }

    // validate the redirectUri.  This is a frequent cause of confusion.
    // if (!keys.redirect_uris || keys.redirect_uris.length === 0) {
    //   throw new Error(invalidRedirectUri)
    // }
    // const redirectUri = keys.redirect_uris[keys.redirect_uris.length - 1]
    const redirectUri = keyFile.redirect_uris[0]
    const parts = new url.URL(redirectUri)
    // console.log(parts)
    // if (
    //   redirectUri.length === 0 ||
    //   parts.port !== port + '' ||
    //   parts.hostname !== 'localhost' ||
    //   parts.pathname !== '/oauth2callback'
    // ) {
    //   throw new Error(invalidRedirectUri)
    // }

    // create an oAuth client to authorize the API call
    this.oAuth2Client = new google.auth.OAuth2(
      keyFile.client_id,
      keyFile.client_secret,
      redirectUri
    )
  }

  // Open an http server to accept the oauth callback. In this
  // simple example, the only request to our webserver is to
  // /oauth2callback?code=<code>
  async authenticate(scopes) {
    return new Promise((resolve, reject) => {
      // grab the url that will be used for authorization
      this.authorizeUrl = this.oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: scopes.join(' ')
      })
      const server = http
        .createServer(async (req, res) => {
          try {
            if (req.url.indexOf('/oauth2callback') > -1) {
              const qs = new url.URL(req.url, 'http://localhost:' + port)
                .searchParams
              res.end(
                'Authentication successful! Please return to the console.'
              )
              server.destroy()
              const { tokens } = await this.oAuth2Client.getToken(
                qs.get('code')
              )
              this.oAuth2Client.credentials = tokens
              resolve(this.oAuth2Client)
            }
          } catch (e) {
            reject(e)
          }
        })
        .listen(port, () => {
          // open the browser to the authorize url to start the workflow
          opn(this.authorizeUrl, { wait: false }).then(cp => cp.unref())
        })
      destroyer(server)
    })
  }
}
// [END auth_oauth2_workflow]
module.exports = new SampleClient()