使用预先存在的访问令牌通过ASP.NET创建YouTube服务

我一直在使用一个网站,用户可以将video上传到共享的YouTube帐户,以便以后访问。 经过大量的工作,我已经能够获得一个主动令牌和可行的刷新令牌。

但是,初始化YouTubeService对象的代码如下所示:

 UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { 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 ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Assembly.GetExecutingAssembly().GetName().Name, }); 

我已经有了一个令牌,我想用我的。 我使用的是ASP.NET 3.5版,所以无论如何我都无法进行async调用。

有没有办法在没有async调用的情况下创建一个YouTubeService对象,并使用我自己的令牌? 有没有一种方法可以在没有授权代理的情况下构建凭证对象?

或者,该应用程序使用YouTube API V2已有一段时间了,并且有一个带有令牌的表单,并针对与API V2中的令牌一起生成的YouTube URI执行了后续操作。 有没有办法用V3实现? 有没有办法使用Javascript上传video,可能还有我可以在我的代码中使用的示例?

注意:我最终将我的Framework升级到4.5以访问谷歌库。

要以编程方式初始化UserCredential对象,您必须构建Flow和TokenResponse。 流需要范围(也就是我们正在寻找凭证的权限)。

 using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Auth.OAuth2.Flows; string[] scopes = new string[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }; GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = XXXXXXXXXX, <- Put your own values here ClientSecret = XXXXXXXXXX <- Put your own values here }, Scopes = scopes, DataStore = new FileDataStore("Store") }); TokenResponse token = new TokenResponse { AccessToken = lblActiveToken.Text, RefreshToken = lblRefreshToken.Text }; UserCredential credential = new UserCredential(flow, Environment.UserName, token); 

希望有所帮助。

目前,官方Google .NET客户端库不适用于.NET Framework 3.5。 (注意:这是一个古老的问题,图书馆自2014年以来一直不支持.NET 3.5。因此该声明也是有效的。)据说你无法为Google创建服务。 NET客户端库使用现有的访问令牌。 也无法使用任何.NET Framework创建访问令牌,您需要创建自己的Idatastore实现并加载刷新令牌。

支持的平台

  1. .NET Framework 4.5和4.6
  2. .NET Core(通过netstandard1.3支持)
  3. Windows 8应用程序
  4. Windows Phone 8和8.1
  5. 便携式类库

话虽如此,你将不得不从头开始自己编写代码。 我做到了,这是可行的。

认证:

您已声明已经拥有刷新令牌,因此我不会介绍如何创建它。 以下是HTTP POST调用

刷新访问令牌请求:

 https://accounts.google.com/o/oauth2/token client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token 

刷新访问令牌响应:

 { "access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ", "token_type" : "Bearer", "expires_in" : 3600 } 

您对YouTube API进行的调用可以将访问令牌添加为授权持有者令牌,也可以将其置于任何请求的末尾

 https://www.googleapis.com/youtube/v3/search?access_token={token here} 

我有关于auth服务器Google 3腿Oauth2流程的所有调用的完整post。 我只是使用普通的webRequets进行所有通话。

 // Create a request for the URL. WebRequest request = WebRequest.Create("http://www.contoso.com/default.html"); // If required by the server, set the credentials. request.Credentials = CredentialCache.DefaultCredentials; // Get the response. WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine (((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams and the response. reader.Close(); response.Close(); 

升级.NET 4+

如果您可以使用库升级到最新版本的.NET将更容易。 这是来自Googles官方文档Web Applications ASP.NET 。 我在我的github帐户上有一些额外的示例代码,它们介绍了如何使用Google Drive API。 Google dotnet会对YouTube数据v3进行抽样调整 。

 using System; using System.Web.Mvc; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Mvc; using Google.Apis.Drive.v2; using Google.Apis.Util.Store; namespace Google.Apis.Sample.MVC4 { public class AppFlowMetadata : FlowMetadata { private static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "PUT_CLIENT_ID_HERE", ClientSecret = "PUT_CLIENT_SECRET_HERE" }, Scopes = new[] { DriveService.Scope.Drive }, DataStore = new FileDataStore("Drive.Api.Auth.Store") }); public override string GetUserId(Controller controller) { // In this sample we use the session to store the user identifiers. // That's not the best practice, because you should have a logic to identify // a user. You might want to use "OpenID Connect". // You can read more about the protocol in the following link: // https://developers.google.com/accounts/docs/OAuth2Login. var user = controller.Session["user"]; if (user == null) { user = Guid.NewGuid(); controller.Session["user"] = user; } return user.ToString(); } public override IAuthorizationCodeFlow Flow { get { return flow; } } } } 

热门提示YouTube不支持您必须坚持使用Oauth2的服务帐户。 只要您的代码一旦继续工作就已经过身份validation。