【问题标题】:Youtube API access is granted but I still have Invalid Credentials error已授予 Youtube API 访问权限,但我仍然有 Invalid Credentials 错误
【发布时间】:2017-03-27 04:51:03
【问题描述】:

尝试测试 YoutubeAPI 的搜索功能,但得到了这个

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

更新: 创建了新帐户,情况还是一样

好吧,我在这里做了什么:

  1. console.developers.google 中创建了项目
  2. 已激活 youtube 数据 api(选择的应用程序或类似的应用程序,而不是 js一),下载的json,看起来是这样的

  1. 首先我调用Authorize 方法(显示新页面,询问权限,我只需单击allow 按钮,一切似乎都正常),但后来我尝试使用Search 我收到 401 错误

这是代码

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文件看起来像这样

【问题讨论】:

  • 使用google开发者控制台的账号与OAuth2中使用的账号无关。它是否弹出网页以验证应用程序?你得到 401 了吗?
  • @DaImTo 是的,我在创建新的YouTubeService 后不久就获得了新页面。一切似乎都还好,但是当我尝试使用 serach 时,我遇到了这个 401 错误

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


【解决方案1】:

好的,我决定一切从头开始,所以,我不知道究竟是什么帮助了我,但这里有一个关于我如何使它工作的简单说明。而且,这是证据:)

所以,首先我创建了一个新项目,设置它的名称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");
               }

           }
       }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多