【发布时间】:2020-01-15 23:16:45
【问题描述】:
如果我使用 API 密钥方法(下面的 RunAPIKey() 方法),它会成功。但是如果我使用 OAuth 方法(下面的RunOauth()),它会失败并出现以下异常:
Error: Google.Apis.Requests.RequestError
Insufficient Permission: Request had insufficient authentication scopes. [403]
Errors [
Message[Insufficient Permission: Request had insufficient authentication scopes.] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
为什么会这样?当然,当浏览器打开 OAuth 页面时,我已经通过我的 YouTube 帐户允许了它。我发现了一个类似的问题,但是添加“强制 SSL”范围的答案不起作用。使用 API 密钥设置 req.Key 也不起作用。我用the official sample code。
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
namespace APITest
{
internal class Test
{
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API");
Console.WriteLine("========================");
try
{
//new Test().RunAPIKey().Wait(); //Works.
new Test().RunOauth().Wait(); //Doesn't work.
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task RunAPIKey()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "apparently_I_cant_show_this",
ApplicationName = this.GetType().ToString()
});
var req = youtubeService.CommentThreads.List("snippet");
req.VideoId = "NK7iIBcsBn4";
req.MaxResults = 5;
var res = await req.ExecuteAsync();
foreach (var item in res.Items)
{
Console.WriteLine(item.Snippet.TopLevelComment.Snippet.TextDisplay);
}
}
private async Task RunOauth()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var req = youtubeService.CommentThreads.List("snippet");
req.VideoId = "NK7iIBcsBn4";
req.MaxResults = 5;
var res = await req.ExecuteAsync();
foreach (var item in res.Items)
{
Console.WriteLine(item.Snippet.TopLevelComment.Snippet.TextDisplay);
}
}
}
}
【问题讨论】:
标签: c# youtube-data-api