带有OAuth2的Youtube API v3返回"收到验证码。关闭..."

时间:2015-03-19 17:19:58

标签: 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);
    }

它运行正常,然后打开一个浏览器窗口询问下面的permition:

OAuth2 Autorization

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

Return from OAuth2

所以,我有两个问题。这条消息的含义是什么?

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

1 个答案:

答案 0 :(得分:2)

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

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

我假设你可以找到C#库来帮助你处理这些重定向和callas,以便接收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