已授予Youtube API访问权限,但我仍然有“无效凭据”错误

时间:2016-11-13 12:14:43

标签: c# oauth-2.0 google-api youtube-api access-token

尝试测试YoutubeAPI的搜索功能,但得到这个 enter image description here

可能是因为我的频道(绑定到我的gmail帐户,我目前在console.developers.google中使用)被禁止了吗?

UPD: 创建新帐户,情况仍然相同

嗯,我在这里做了什么:

  1. console.developers.google
  2. 中创建了项目
  3. 激活youtube数据api(选择这样的app或somth,而不是 js one),下载了json,看起来像那样
  4. enter image description here

    1. 首先我调用Authorize方法(新页面显示,询问权限,我只点击allow按钮,一切似乎都好),但后来我尝试使用Search 我得到401错误
    2. 继承人的代码

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      
      namespace WebApplication3.Services.ServiceAuthoriaztion.Impl
      {
          using System.Data.Entity.Core.Metadata.Edm;
          using System.IO;
          using System.Threading;
          using Google.Apis;
          using Google.Apis.Auth.OAuth2;
          using Google.Apis.Services;
          using Google.Apis.Util.Store;
          using Google.Apis.YouTube.v3;
      
      
          public class Youtube : ICustomService
          {
              private static YouTubeService _currentYouTubeService;
      
              public void Authorize()
              {
                  UserCredential userCreds;
                 ;
                  var filePath = string.Format("{0}{1}",AppDomain.CurrentDomain.BaseDirectory, @"App_Data\client_id.json");
                  using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                  {
                      userCreds = GoogleWebAuthorizationBroker.AuthorizeAsync(
                          GoogleClientSecrets.Load(stream).Secrets,
                          new[] {YouTubeService.Scope.YoutubeReadonly},
                          "user",
                          CancellationToken.None,
                          new FileDataStore("YouTubeData")
                          ).Result;
                  }
      
                  _currentYouTubeService = new YouTubeService(new BaseClientService.Initializer
                  {
                      HttpClientInitializer = userCreds,
                      ApplicationName = "yttest"
                  });
      
                  SerachTest();
      
              }
      
              private void SerachTest()
              {
                  var searchListRequest = _currentYouTubeService.Search.List("snippet");
                  searchListRequest.Q = "Google"; // Replace with your search term.
                  searchListRequest.MaxResults = 50;
      
                  // Call the search.list method to retrieve results matching the specified query term.
                  var searchListResponse = searchListRequest.Execute();
      
                  var asa = new List<string>();
      
              }
          }
      }
      

      UPD2: 试过其他类型的应用程序 - 没有帮助。 JSON文件看起来像那样 enter image description here

1 个答案:

答案 0 :(得分:0)

好吧,我决定从头开始一切,所以,我不知道究竟对我有什么帮助,但这里有一个关于我如何使它发挥作用的简单说明。而且,这里是证明:) enter image description here

所以,首先我创建了新项目,设置了它的名称DanilTestApp

其次,在那里打开了YouTube Data API

当我创建新凭据时,选择OAuth Client ID然后选择Other作为类型。

准备就绪后,我刚刚下载了JSON。

然后在我的代码中我决定添加刷新令牌功能,所以现在它看起来像这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication3.Services.ServiceAuthoriaztion.Impl
{
    using System.Data.Entity.Core.Metadata.Edm;
    using System.IO;
    using System.Threading;
    using Google.Apis;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    using Google.Apis.YouTube.v3;


    public class Youtube : ICustomService
    {
        private static YouTubeService _currentYouTubeService;

        public void Authorize()
        {
            UserCredential userCreds; 
            var filePath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @ "App_Data\client_id.json");
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                userCreds = GoogleWebAuthorizationBroker.AuthorizeAsync(
                 GoogleClientSecrets.Load(stream).Secrets,
                 new[] {
          YouTubeService.Scope.YoutubeReadonly
                 },
                 "user",
                 CancellationToken.None,
                 new FileDataStore("YouTubeData")
                ).Result;
            }

            RefreshToken(userCreds);

            _currentYouTubeService = new YouTubeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = userCreds,
                ApplicationName = "DanilTestApp"
            });

            SerachTest();

        }

        private void SerachTest()
        {
            var searchListRequest = _currentYouTubeService.Search.List("snippet");
            searchListRequest.Q = "Google"; // Replace with your search term.
            searchListRequest.MaxResults = 50;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = searchListRequest.Execute();

            var asa = new List<string>();

        }
        //might not work, but something like this, got working code at home, office right now
        private void UpdateTokenIfExpired(UserCredential credential)
        {
           if (credential.Token.IsExpired(credential.Flow.Clock))
           {

               Console.WriteLine("The access token has expired, refreshing it");
               if (credential.RefreshTokenAsync(CancellationToken.None).Result)
               {
                   Console.WriteLine("The access token is now refreshed");
               }
               else
               {
                   throw new Exception("refresh token failed");
               }

           }
       }

    }
}