尝试获取用户 Youtube 频道时出现权限不足错误
Posted
技术标签:
【中文标题】尝试获取用户 Youtube 频道时出现权限不足错误【英文标题】:Insufficient permission error when trying to fetch user Youtube Channels 【发布时间】:2021-12-10 09:12:33 【问题描述】:我已通过 Youtube 帐户进行身份验证,并成功获取了访问令牌。现在我希望使用以下代码获取用户的 Youtube 频道:
async fetchYoutubeChannels()
let accessToken = ....;
const authCredentials = accessToken;
const oauth2Client = initOAuth2Client(); //Oauth2 Client initialized at the top with secret, redirect url and and client id
oauth2Client.setCredentials(authCredentials);
oauth2Client.on('tokens', async (tokens) =>
if (tokens.refresh_token)
//Save new token
);
let service = google.youtube('v3');
service.channels.list(
auth: oauth2Client,
part: 'snippet,contentDetails,statistics',
, function (err, response)
if (err)
console.log('The Youtube API returned an error: ' + err);
return;
let channels = response.data;
console.log(`Retrieved Channels = $JSON.stringify(channels, null, 2)`);
);
但我得到的只是这个错误信息:
Youtube API 返回错误:错误:权限不足
我错过了什么?
任何想法将不胜感激。 谢谢。
【问题讨论】:
您在代码中遗漏了什么您要求的范围是什么? 【参考方案1】:错误:权限不足
表示用户已授权您的应用程序,但未授予您访问此方法所需的权限。
我假设你正在关注quickstart nodejs,只是忽略了一些代码。
注意 get channel 方法如何传递作为授权的一部分创建的 auth 参数。您似乎正在尝试通过设置访问令牌来手动创建它。您应该让代码创建访问令牌,因为它将在适当的范围内创建。
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);
);
来自 cmets
如何获取 youtube 帐户的用户名。是 oauth2 过程中检索到的用户显示名称吗?
youtube api 是基于频道而不是基于用户的。您可以访问用户频道。不是技术上用户自己activites 可能会给你一些关于用户授权你访问的频道的信息,但我还没有真正尝试过。
错误:未选择过滤器。预期之一:mySubscribers、id、categoryId、mine、managedByMe、forUsername
Channels: list 要求您发送过滤器。查看Filters (specify exactly one of the following parameters)
部分
【讨论】:
天哪!!!非常感谢您的详尽解释。你完全正确!!事实上,在身份验证过程中,我实际上忘记选中复选框以允许应用程序管理 youtube 帐户,这就是原因。我最终重新验证并检查了这些框,那个阶段似乎被覆盖了。但是,我面临更多问题,即此错误No filter selected. Expected one of: mySubscribers, id, categoryId, mine, managedByMe, forUsername
。如何获取 youtube 帐户的用户名。是 oauth2 过程中检索到的用户显示名称吗?
检查更新答案以获得额外帮助以上是关于尝试获取用户 Youtube 频道时出现权限不足错误的主要内容,如果未能解决你的问题,请参考以下文章
如何从 YouTube 频道 ID 获取用户的 Google+ ID