YouTube Data API v3:使用服务帐户删除视频:请求中未授权的客户端或范围



我试图删除一个或多个视频使用一个简单的c#应用程序(我打算使用Windows服务以后),我得到这个错误:

Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""
   at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:codegoogle.comgoogle-api-dotnet-clientdefaultToolsGoogle.Apis.ReleasebinDebugtestdefaultSrcGoogleApisApisRequestsClientServiceRequest.cs:line 93

上传视频工作完美。对于这两个操作,我使用相同的初始化方法:

private static YouTubeService AuthorizeYoutubeService()
{
  string serviceAccountEmail = "...@developer.gserviceaccount.com";
  string keyFilePath = "Warehouse<...>.p12";
  string userAccountEmail = "login@gmail.com";
  if (!File.Exists(keyFilePath))
  {
    System.Windows.Forms.MessageBox.Show("Secret file not found!");
    return null;
  }
  var scope = new string[] { YouTubeService.Scope.Youtube };
  var cert = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
  try
  {
    ServiceAccountCredential credential = new ServiceAccountCredential
      (new ServiceAccountCredential.Initializer(serviceAccountEmail)
      {
        Scopes = scope,
        User = userAccountEmail
      }.FromCertificate(cert));
    var service = new YouTubeService(new BaseClientService.Initializer
    {
      HttpClientInitializer = credential,
      ApplicationName = "warehouse"
    });
    return service;
  }
  catch (Exception ex)
  {
    System.Windows.Forms.MessageBox.Show(ex.Message);
    return null;
  }
}

与简单上传视频的区别在于定义的Scope: YouTubeService.Scope.YoutubeUpload。当我尝试使用它删除视频时,我得到一个insufficientPermissions (403)错误。因此,在查看文档后,我将其更改为YouTubeService.Scope.Youtube.

下面是我要使用的代码:

  var youtubeService = AuthorizeYoutubeService();
  foreach (string id in deleteIds)
  {
    var videoDeleteRequest = youtubeService.Videos.Delete(id);    
    var result = videoDeleteRequest.Execute();
  }

其中deleteIds是包含现有视频id的11个字符串的列表。我在开发者控制台中启用了YouTube Data API。我已经通过NuGet安装了API,我不认为包有任何问题。

我是Google开发的新手,所有类似的问题都是关于日历API的。

谢谢你的帮助。

我最终做的是重新设置连接到谷歌帐户的应用程序列表,并从头开始重新设置。由于某些原因,我的应用被添加了2次

最新更新