Youtube API访问被授予,但我仍然有无效凭证错误 [英] Youtube API access is granted but I still have Invalid Credentials error

查看:592
本文介绍了Youtube API访问被授予,但我仍然有无效凭证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图测试YoutubeAPI的搜索功能,但获得这



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



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



那么,我在这里做了什么:


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

p>


  1. 首先我调用 Authorize 方法(新页面显示,询问权限,我只需点击 allow 按钮,一切似乎都没问题),但是我试图使用搜索
    ,我得到401错误

继承代码

 使用System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;

命名空间WebApplication3.Services.ServiceAuthoriaztion.Impl
{
using System.Data.Entity.Core.Metadata.Edm;
使用System.IO;
使用System.Threading;
使用Google.Apis;
使用Google.Apis.Auth.OAuth2;
使用Google.Apis.Services;
使用Google.Apis.Util.Store;
使用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,
新FileDataStore(YouTubeData)
).Result ;
}

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

SerachTest();


$ b private void SerachTest()
{
var searchListRequest = _currentYouTubeService.Search.List(snippet);
searchListRequest.Q =Google; //替换为您的搜索字词。
searchListRequest.MaxResults = 50;

//调用search.list方法检索与指定查询词相匹配的结果。
var searchListResponse = searchListRequest.Execute();

var asa = new List< string>();



$ b code

$ b

UPD2:
尝试了其他类型的应用 - 也没有帮助。
JSON文件看起来像

解决方案

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

因此,首先我创建了新项目,设置名称它 DanilTestApp

$ b 其次,开启 YouTube数据API 那里。



在创建新凭证时,选择 OAuth客户端ID ,然后选择其他作为类型。



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

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

命名空间WebApplication3.Services.ServiceAuthoriaztion.Impl
{
using System.Data.Entity.Core.Metadata.Edm;
使用System.IO;
使用System.Threading;
使用Google.Apis;
使用Google.Apis.Auth.OAuth2;
使用Google.Apis.Services;
使用Google.Apis.Util.Store;
使用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(新BaseClientService.Initializer
{
HttpClientInitializer = userCreds,
ApplicationName =DanilTestApp
});

SerachTest();


$ b private void SerachTest()
{
var searchListRequest = _currentYouTubeService.Search.List(snippet);
searchListRequest.Q =Google; //替换为您的搜索字词。
searchListRequest.MaxResults = 50;

//调用search.list方法检索与指定查询词相匹配的结果。
var searchListResponse = searchListRequest.Execute();

var asa = new List< string>();


//可能不起作用,但是像这样,在家里得到了工作代码,办公室现在
private void UpdateTokenIfExpired(UserCredential凭证)
{
if(credential.Token.IsExpired(credential.Flow.Clock))
{

Console.WriteLine(访问令牌已过期,刷新它);
if(credential.RefreshTokenAsync(CancellationToken.None).Result)
{
Console.WriteLine(访问令牌现在被刷新);
}
else
{
抛出新的异常(refresh token failed);






$ $ $ $ $ pre >

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

解决方案

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

           }
       }

    }
}

这篇关于Youtube API访问被授予,但我仍然有无效凭证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆