使用预先存在的访问令牌通过 ASP.NET 创建 YouTube 服务
Creating a YouTube Service via ASP.NET using a pre-existing Access Token
我一直在开发一个网站,供用户将视频上传到共享的 YouTube 帐户供以后访问。经过大量工作后,我已经能够获得一个 Active Token 和可行的 Refresh Token。
但是,初始化 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 已有一段时间,并且有一个采用令牌的表单,并对与令牌一起生成的 YouTube URI 执行 post 操作在 API V2 中。有什么方法可以用 V3 实现吗?有没有一种方法可以使用 Javascript 上传视频,可能还有一个我可以在我的代码中使用的示例?
注意:我最终将我的框架升级到 4.5 以访问 google 库。
要以编程方式初始化 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 client library 不适用于 .NET Framework 3.5。 (注意:这是一个老问题,该库自 2014 年以来一直不支持 .NET 3.5。因此该声明在那时也是有效的。) 话虽如此,您不会能够使用现有的访问令牌为 Google .NET 客户端库创建服务。也无法使用任何 .NET Framework 使用访问令牌创建它,您需要创建自己的 Idatastore
实现并加载刷新令牌。
Supported Platforms
- .NET Framework 4.5 and 4.6
- .NET Core (via netstandard1.3 support)
- Windows 8 Apps
- Windows Phone 8 and 8.1
- Portable Class Libraries
话虽如此,您将不得不自己从头开始编写代码。我已经做到了,而且是可行的。
身份验证:
您已经声明您已经拥有刷新令牌,所以我不会讨论如何创建它。
以下是 HTTPPOST 调用
刷新访问令牌请求:
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}
我对所有调用的身份验证服务器 Google 3 legged Oauth2 flow. I just use normal webRequets 都有一个完整的 post。
// 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 将会容易得多。这是来自 Google 的官方文档 Web Applications ASP.NET. I have some additional sample code on my github account which shoes how to use the Google Drive API. Google dotnet samples YouTube data 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 的服务帐户。只要您对代码进行了身份验证,它就应该继续工作。
我一直在开发一个网站,供用户将视频上传到共享的 YouTube 帐户供以后访问。经过大量工作后,我已经能够获得一个 Active Token 和可行的 Refresh Token。
但是,初始化 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 已有一段时间,并且有一个采用令牌的表单,并对与令牌一起生成的 YouTube URI 执行 post 操作在 API V2 中。有什么方法可以用 V3 实现吗?有没有一种方法可以使用 Javascript 上传视频,可能还有一个我可以在我的代码中使用的示例?
注意:我最终将我的框架升级到 4.5 以访问 google 库。
要以编程方式初始化 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 client library 不适用于 .NET Framework 3.5。 (注意:这是一个老问题,该库自 2014 年以来一直不支持 .NET 3.5。因此该声明在那时也是有效的。) 话虽如此,您不会能够使用现有的访问令牌为 Google .NET 客户端库创建服务。也无法使用任何 .NET Framework 使用访问令牌创建它,您需要创建自己的 Idatastore
实现并加载刷新令牌。
Supported Platforms
- .NET Framework 4.5 and 4.6
- .NET Core (via netstandard1.3 support)
- Windows 8 Apps
- Windows Phone 8 and 8.1
- Portable Class Libraries
话虽如此,您将不得不自己从头开始编写代码。我已经做到了,而且是可行的。
身份验证:
您已经声明您已经拥有刷新令牌,所以我不会讨论如何创建它。 以下是 HTTPPOST 调用
刷新访问令牌请求:
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}
我对所有调用的身份验证服务器 Google 3 legged Oauth2 flow. I just use normal webRequets 都有一个完整的 post。
// 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 将会容易得多。这是来自 Google 的官方文档 Web Applications ASP.NET. I have some additional sample code on my github account which shoes how to use the Google Drive API. Google dotnet samples YouTube data 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 的服务帐户。只要您对代码进行了身份验证,它就应该继续工作。