【问题标题】:TypeError: Cannot read property 'redirect_uris' of undefined Youtube Data API authentication NodeJSTypeError:无法读取未定义的 Youtube 数据 API 身份验证 NodeJS 的属性“redirect_uris”
【发布时间】:2020-12-06 04:47:37
【问题描述】:

我有一个网络应用程序,我希望通过该应用程序能够创建播放列表、将视频添加到播放列表、删除视频等到我的 youtube 频道。我创建了一个服务帐户并下载了服务帐户凭据密钥文件,并在 Google Developer Console 中设置了我的 OAuth 2.0 客户端 ID。 为了验证我的应用,我按照README.md 中的说明操作google-api-nodejs-client 此处https://github.com/googleapis/google-api-nodejs-client - 在服务帐户凭据

这是我的控制器文件... 我应该注意到该项目使用 ES 模块,因此"type": "module" 设置在package.json 中。这就是为什么你会注意到例如我将 __dirname 作为实用程序导入的原因,因为 ES 模块不支持常规的 __dirname

import googleapi from "googleapis";
const { google } = googleapi;
import Auth from "@google-cloud/local-auth";
const { authenticate } = Auth;
import path from "path";
import __dirname from "../utils/dirname.js";

async function initialize() {
  try {
    const auth = await authenticate({
      keyfilePath: path.join(__dirname, "../service_account_credentials.json"),
      scopes: ["https://www.googleapis.com/auth/youtube"],
    });
    console.log("Auth details");
    console.log(auth);
    google.options({ auth });
  } catch (e) {
    console.log(e);
  }
}
initialize();

const oauth2Client = new google.auth.OAuth2(
  "YOUR_CLIENT_ID",
  "YOUR_CLIENT_SECRET",
  "http://localhost:5000/oauth2callback"
);

// initialize the Youtube API library
const youtube = google.youtube({ version: "v3", auth: oauth2Client });

class YoutubeController {
  static async createPlaylist(req, res) {
    const { name } = req.body;
    const playlist = await youtube.playlists.insert({
      part: "snippet,status",
      resource: {
        snippet: {
          title: name,
          description: `${name} videos.`,
        },
        status: {
          privacyStatus: "private",
        },
      },
    });

    res.json(playlist);
  }
}

initialize 函数是引发错误的函数,我不太明白。我想正因为如此,当我向在类中调用方法createPlaylist 的路由发出POST 请求时,我会返回No access, refresh token or API key is set.

我一直在阅读文档,试图了解一切是如何流动的,但我有点卡住了。

在这里提出了类似的问题 - TypeError: Cannot read property 'redirect_uris' of undefined,但没有答案,建议的工作流程不适用于我的情况,因此非常感谢您对此提供的帮助。

【问题讨论】:

    标签: node.js google-api google-oauth youtube-data-api google-api-nodejs-client


    【解决方案1】:

    服务帐号

    YouTube API 不支持您需要使用 OAuth2 的服务帐户身份验证。

    OAuth2 授权

    您可能需要考虑关注YouTube API quick start for nodejs.

    问题是您正在使用它不支持的 YouTube API 的服务帐户身份验证。

    var fs = require('fs');
    var readline = require('readline');
    var {google} = require('googleapis');
    var OAuth2 = google.auth.OAuth2;
    
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/youtube-nodejs-quickstart.json
    var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
    var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
        process.env.USERPROFILE) + '/.credentials/';
    var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
    
    // Load client secrets from a local file.
    fs.readFile('client_secret.json', function processClientSecrets(err, content) {
      if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
      }
      // Authorize a client with the loaded credentials, then call the YouTube API.
      authorize(JSON.parse(content), getChannel);
    });
    
    /**
     * 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) {
      var clientSecret = credentials.installed.client_secret;
      var clientId = credentials.installed.client_id;
      var redirectUrl = credentials.installed.redirect_uris[0];
      var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
    
      // Check if we have previously stored a token.
      fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
          getNewToken(oauth2Client, callback);
        } else {
          oauth2Client.credentials = 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 to call with the authorized
     *     client.
     */
    function getNewToken(oauth2Client, callback) {
      var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
      });
      console.log('Authorize this app by visiting this url: ', authUrl);
      var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
      rl.question('Enter the code from that page here: ', function(code) {
        rl.close();
        oauth2Client.getToken(code, function(err, token) {
          if (err) {
            console.log('Error while trying to retrieve access token', err);
            return;
          }
          oauth2Client.credentials = token;
          storeToken(token);
          callback(oauth2Client);
        });
      });
    }
    
    /**
     * Store token to disk be used in later program executions.
     *
     * @param {Object} token The token to store to disk.
     */
    function storeToken(token) {
      try {
        fs.mkdirSync(TOKEN_DIR);
      } catch (err) {
        if (err.code != 'EEXIST') {
          throw err;
        }
      }
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) throw err;
        console.log('Token stored to ' + TOKEN_PATH);
      });
    }
    
    /**
     * Lists the names and IDs of up to 10 files.
     *
     * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
     */
    function getChannel(auth) {
      var service = google.youtube('v3');
      service.channels.list({
        auth: auth,
        part: 'snippet,contentDetails,statistics',
        forUsername: 'GoogleDevelopers'
      }, function(err, response) {
        if (err) {
          console.log('The API returned an error: ' + err);
          return;
        }
        var channels = response.data.items;
        if (channels.length == 0) {
          console.log('No channel found.');
        } else {
          console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                      'it has %s views.',
                      channels[0].id,
                      channels[0].snippet.title,
                      channels[0].statistics.viewCount);
        }
      });
    }
    

    代码无耻地从YouTube API quick start for nodejs.撕下来

    后端访问

    由于 YouTube API 不支持服务帐户。从后端服务访问数据可能很棘手,但并非不可能。

    1. 在本地运行您的应用程序一次。
    2. Aurhtoirze 访问您的帐户数据。
    3. 在您的代码中找到存储的凭据,它们应包含刷新令牌。
    4. 将此刷新令牌保存为您的应用程序的一部分。
    5. 设置您的代码以在加载时读取此刷新令牌。

    不幸的是,我不是 node.js 开发人员,所以我无法帮助您编写所需的代码。如果您可以找到该库以及如何加载该库,则该库应该将内容存储到凭据对象中,那么您应该能够执行我的建议。

    我会先深入研究 storeToken(token); 正在做什么。

    【讨论】:

    • 那么有没有办法避免导航到不同的 URL 进行身份验证?我想也许可以在后端静默进行身份验证,然后将视频发布到我的频道。
    • No Oauth2 要求用户出示同意书才能同意访问​​您的应用程序。您只需存储刷新令牌并在后端使用该刷新令牌即可执行此操作,然后您将能够根据需要访问该帐户。 access_type: 'offline',给你你需要的刷新令牌。
    • 我的用例有点奇怪。与将一些视频文件存储在其他地方相反,我认为也许可以将它们上传到我的 youtube 频道并将它们拉入我的网站。使用 Oauth2,这意味着我每次从另一台计算机打开站点时都必须验证自己的身份,并且没有其他人可以代表我上传。因此,我的用例似乎是不可能的,所以我猜谷歌云存储可以吗?
    • 实际上,使用我的解决方案,您只需在后端运行脚本并使用存储的刷新令牌访问您的帐户后,对您的应用程序进行身份验证。假设您将它们公开上传到您的频道,那么您应该能够在您的网站上显示它们。抱歉,我无法为您提供云存储方面的帮助,但我认为这将是一个相当昂贵的选择。
    • 刚刚看到您对后端访问的修改。我会试试的。如果我弄清楚了,我会在此处包含代码。谢谢你的朋友。
    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2021-12-05
    • 2021-02-24
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2015-07-02
    • 2017-03-06
    相关资源
    最近更新 更多