Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用预先存在的访问令牌通过ASP.NET创建YouTube服务_Javascript_C#_Asp.net_Youtube Api_Google Oauth - Fatal编程技术网

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

Javascript 使用预先存在的访问令牌通过ASP.NET创建YouTube服务,javascript,c#,asp.net,youtube-api,google-oauth,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 G

我一直在开发一个网站,用户可以将视频上传到一个共享的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执行post操作。有没有一种方法可以通过V3实现这一点?有没有一种方法可以使用Javascript上传视频,或者我可以在代码中使用的一个示例?

注意:我最终将框架升级到4.5以访问google库

要以编程方式初始化UserCredential对象,您必须构建一个流和令牌响应。流需要一个作用域(也称为我们正在寻找的凭据权限)

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.api.Auth.OAuth2;
使用Google.api.Auth.OAuth2.Responses;
使用Google.api.Auth.OAuth2.Flows;
字符串[]范围=新字符串[]{
YouTubeService.Scope.Youtube,
YouTubeService.Scope.YoutubeUpload
};
GoogleAuthorizationCodeFlow=新的GoogleAuthorizationCodeFlow(新的GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets=新的ClientSecrets
{
ClientId=XXXXXXXXX,目前该官员不支持.NET Framework 3.5。(注意:这是一个老问题,该库自2014年以来一直不支持.NET 3.5。因此该声明在当时也是有效的。)也就是说,您不能使用现有的访问令牌为Google.NET客户端库创建服务。也不可能使用任何.NET Framework的访问令牌创建服务。您需要创建自己的
Idatastore
实现并加载刷新令牌

支撑平台

  • .NET Framework 4.5和4.6
  • .NET核心(通过netstandard1.3支持)
  • Windows 8应用程序
  • Windows Phone 8和8.1
  • 可移植类库
  • 也就是说,你必须自己从头开始编写代码。我已经完成了,而且是可行的

    身份验证:

    你已经声明你已经有了你的刷新令牌,所以我不会讨论如何创建它。 下面是一个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}
    
    我有一篇关于所有对身份验证服务器的调用的完整文章。我只对所有调用使用普通

    // 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官方文档。我的github帐户上有一些额外的示例代码,这些代码说明了如何使用Google Drive API


    顶部提示YouTube不支持服务帐户,您必须坚持使用Oauth2。只要您对代码进行了身份验证,代码就可以继续工作。

    如果您使用的是framework 3.5,那么带有异步调用的库将无法工作,它应该根据fw 4.0或更高版本进行编译…是的。这就是为什么我需要一个不支持此功能的解决方案不要依赖异步调用。如果不是必须的话,我不想升级框架。哦,天哪,现在是2017年,我遇到了同样的事情。你有没有发现这个问题?澄清一下,同样的问题,但原因不同;我正试图在没有UI的云中做一些这方面的工作。但是,我应该已经有了我的请求中出现了一个访问令牌。我确实找到了如何以编程方式初始化UserCredential对象。我将在回答中发布我的代码,因为它太长,无法发表评论。您声明您使用的是.net 3.5。Google.net客户端库的最小值为.net 4.0,不再更新。net 4.5是当前支持的target。库不会在您的项目中工作。除非您更新了框架。这也不会工作,因为FileDatastore需要一个刷新令牌才能工作,并且问题状态为access令牌。至于初始令牌。这很容易。我构建了一个单独的表单来为该令牌种子,然后将其存储在数据库中。当是时候使用它了,我检查我的令牌过期,如果它过期,我会通过存储的刷新令牌刷新它。这个lblActiveToken和这个lblRefreshToken是什么?你从用户那里获取这些输入吗?我想使用我的帐户从播放列表中检索视频列表。忘了提及-我实际上使用的是.NET 4.6.2。我有访问权限对于SDK,但似乎有很多隐含的行为,我必须在web请求方面处理。我编辑了我的答案,添加了一些关于如何使用库的信息。你真的应该打开你自己的问题,这是针对3.5的,因此它与你的问题没有关系。如果你需要更多帮助,请告诉我我有youtube上也有一些教程。
    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; }
            }
        }
    }