c# - 带有 OAuth2 的 Youtube API v3 返回 "Received verification code. Closing..."

标签 c# oauth-2.0 youtube-api

我正在尝试使用 C# Win 应用程序在 YouTube 中上传视频,代码如下:

    public Form1()
    {
        InitializeComponent();

        Console.WriteLine("YouTube Data API: Upload Video");
        Console.WriteLine("==============================");

        try
        {
            new UploadVideo().Run().Wait();
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                //Console.WriteLine("Error: " + e.Message);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

这是UploadVideo类:

internal class UploadVideo
{
    public async Task Run()
    {
        UserCredential credential;
        using (var stream = new FileStream(@"C:\Users\23679\Downloads\client_secret.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { YouTubeService.Scope.YoutubeUpload },
                "user",
                CancellationToken.None
            );
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });

        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = "Default Video Title";
        video.Snippet.Description = "Default Video Description";
        video.Snippet.Tags = new string[] { "tag1", "tag2" };
        video.Snippet.CategoryId = "22";
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "private";
        var filePath = @"C:\Users\23679\Downloads\spacetestSMALL.wmv";

        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            await videosInsertRequest.UploadAsync();
        }

    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                break;

            case UploadStatus.Failed:
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }

它运行正常,然后打开一个浏览器窗口询问许可,如下所示:

OAuth2 Autorization

问题是我确认后他在浏览器中返回此消息:

Return from OAuth2

所以,我有两个问题。此消息意味着什么?

第二个是,在那之后,应该发生什么?因为,视频没有上传,调试也没有继续...

最佳答案

我不熟悉 C#,但对 OAuth 2.0 授权代码授予有一些基本了解。我制作了一个网络序列图,可以帮助您。

在您共享的第一个屏幕截图中,URI 包含带有您的回调网址的redirect_uri 查询参数。此请求使用 HTTP 302 重定向到带有 code=... 查询参数的回调 uri 来获取响应。您的应用程序应该处理此请求并将此代码交换为access_token

我的假设是,您可以找到 C# 库来帮助您处理这些重定向和调用,以便接收 access_tokenrefresh_token,如 RFC 中所示:

来自 OAuth 2.0 兼容服务器的响应:

HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQ&state=xyz

本地应用程序应该伪造此请求:

 POST /token HTTP/1.1
 Host: server.example.com
 Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
 Content-Type: application/x-www-form-urlencoded     
 
 grant_type=authorization_code&code=SplxlOBeZQQ
 &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

来自 OAuth 2.0 兼容服务器的响应:

 HTTP/1.1 200 OK
 Content-Type: application/json;charset=UTF-8
 Cache-Control: no-store
 Pragma: no-cache

 {
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
   "example_parameter":"example_value"
 }

我制作的这个网络序列图可能是一个很好的解释。

enter image description here

关于c# - 带有 OAuth2 的 Youtube API v3 返回 "Received verification code. Closing...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151050/

相关文章:

c# - 如何从 C# 代码中拉伸(stretch) DataGrid 列?

OutputStream 上的 Java 自动 HTTP header

javascript - REST API - CORS 问题

java - Spring Security - 实现 oauth2 sso

youtube-api - 有没有办法通过 YouTube API v3 添加评论?

google-cloud-platform - Google Cloud 函数和服务帐户

c# - Visual Studio 2010 - 修复 "using"功能?

c# - 无法访问 SqlTransaction 对象以在 catch block 中回滚

salesforce - 为什么 Salesforce OAuth2 将我从一个实例 na3 for ex 重定向到另一个 na9

html - Youtube API 控件在屏幕上留下黑色部分