Youtube API access is granted but I still have Invalid Credentials error

邮差的信 提交于 2020-01-05 04:37:06

问题


Trying to test search functions of the YoutubeAPI, but getting this

Could it be because of my channel(which is binded to my gmail account, which I currently using in console.developers.google) was banned?

UPD: Created new account, situation still the same

Well, what I've have done here:

  1. created porject in console.developers.google
  2. activated youtube data api(choosed app or somth like this, not the js one), downloaded json, which looks like that

  1. First I call the Authorize method (new page shows, asking permission, where I just clicking allow button, and everything seems like ok), but then I trying to use Search and I get 401 error

heres the code

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: Tried other type of app - not helped either. JSON file looks like that


回答1:


Okay, I decided start everything from scratch, so, I don't know what exactly helped me but here's a simple instructions about how I made it work. And also, here's the proof :)

So, first I created new project, set name of it DanilTestApp.

Second, turned on YouTube Data API there.

When I was creating new credentials, choosed OAuth Client ID and then, as a type, choosed Other.

After it was ready I just downloaded JSON.

Then in my code I decide to add refreshing token functionality, so now it looks like this

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");
               }

           }
       }

    }
}


来源:https://stackoverflow.com/questions/40573697/youtube-api-access-is-granted-but-i-still-have-invalid-credentials-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!