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

时间:2015-04-28 21:28:53

标签: javascript c# asp.net youtube-api google-oauth

我一直在使用一个网站,用户可以将视频上传到共享的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调用。

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

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

2 个答案:

答案 0 :(得分:4)

注意:我最终将我的Framework升级到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);

希望有所帮助。

答案 1 :(得分:4)

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

  

支持的平台

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

据说你将不得不从头开始自己编码。我做到了,它是可行的。

身份验证:

您已声明已拥有刷新令牌,因此我不会介绍如何创建它。 以下是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 legged Oauth2 flow的所有调用都有完整的帖子。我只是使用普通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 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的服务帐户。只要您在代码继续工作后对其进行了身份验证,就可以了。