node.js - 错误: The provided keyfile does not define a valid redirect URI

标签 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"]}}
<小时/>

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

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

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

我是 Node.js 的初学者,发现很难弄清楚它是什么。需要使其发挥作用。 我很高兴得到一些答案,帮助我重回正轨。

最佳答案

我也遇到了同样的问题。在我看来,他们的示例文件 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()

关于node.js - 错误: The provided keyfile does not define a valid redirect URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257756/

相关文章:

javascript - 导入自定义 CommonJS 模块失败

json - 如何使用 Swift 访问此 JSON 字典中的特定值?

asp.net - Z-Index属性不适用于youtube视频

python - 集成pylint和github评论评论

javascript - 我隐藏的 DIV 中的 Youtube 视频仅在显示 DIV 后才开始加载

ios - 将本地视频嵌入到 UIView 中

node.js - 如何为两个都需要 socket.io 的应用程序设置 NGINX 的端口 80 的反向代理?

javascript - 从node.js将文件上传到Azure后如何获取blob URL

node.js - 按键下划线聚合哈希

json - Youtube Api 获取用户订阅的 channel