我想使用客户端登录在 youtube 上上传视频。未经打开网页许可

I want to upload video on youtube using client side login. without open web page permission

当我使用客户端登录将视频上传到 YouTube 时。第一次重定向到 UI 以获得权​​限。

我想上传而不重定向到网页。我需要在服务器上执行这段代码。

这是我的代码。

    private async Task<string> Run(string title, string description, string filepath)
        {

            var videoID = string.Empty;
            try
            {
                logger.Info(string.Format("[uploading file on youTube Title: {0}, Description: {1}, filePath: {2}]", title, description, filepath));
                UserCredential credential;
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    logger.Info("[Load credentials from google start]");
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                    logger.Info("[Load credentials from google end]");

                }
                logger.Info("YouTubeApiKey {0}", System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"]);
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                  {
                      HttpClientInitializer = credential,
                      ApiKey = System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"],
                      ApplicationName = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]
                  });

                logger.Info("ApplicationName {0}", System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);


                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = title;
                video.Snippet.Description = description;
                //video.Snippet.Tags = new string[] { "tag1", "tag2" };
                // video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "public"; // or "private" or "public"
                var filePath = filepath; // Replace with path to actual movie file.


                 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();

            }
                return videoID;
            }
            catch (Exception e)
            {
                logger.ErrorException("[Error occurred in Run ]", e);
            }
            return videoID;
  }

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

您的代码所做的一切都是正确的。 YouTube API 不允许纯服务器身份验证(服务帐户)。您上传文件的唯一选择是使用 Oauth2 并在第一次验证您的代码。

我只是建议您做一个小改动,添加文件数据存储。这将为您存储身份验证。一旦您通过 Web 浏览器对其进行了身份验证,您就无需再次执行此操作。

/// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { YouTubeService.Scope.Youtube,  // view and manage your YouTube account
                                             YouTubeService.Scope.YoutubeForceSsl,
                                             YouTubeService.Scope.Youtubepartner,
                                             YouTubeService.Scope.YoutubepartnerChannelAudit,
                                             YouTubeService.Scope.YoutubeReadonly,
                                             YouTubeService.Scope.YoutubeUpload}; 

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.YouTube.Auth.Store")).Result;

                YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "YouTube Data API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;

            }
         }

像这样调用上面的方法:

// Authenticate Oauth2
            String CLIENT_ID = "xxxxxx-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
            String CLIENT_SECRET = "NDmluNfTgUk6wgmy7cFo64RV";
            var service = Authentication.AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, "SingleUser");

您的代码第一次需要进行身份验证。一旦其经过身份验证的文件数据存储将文件存储在您计算机上的 %appData% 中。此后每次运行时,它将使用存储在 %appData% 中的刷新令牌再次获得访问权限。

YouTube API Sample project

中窃取的代码