Youtube v3 api 401未经授权

时间:2013-06-25 13:03:08

标签: c# youtube-api

我正在尝试使用youtube api的v3上传文件而不使用c#库。我真的不能使用该库,因为我正在创建自己的库,允许我使用一些常见的apis(youtube,vimeo,facebook等)

我已经获得了访问令牌和刷新令牌,这很好。现在我需要使用此处定义的youtube可恢复上传文件上传文件:

https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol

但由于某种原因,我的代码回来时发出401 Unauthorized错误,但我看不出原因。 这是我创建请求的代码:

    private void CreateUploadRequest(SynchronisedAsset asset)
    {
        var endPoint = api.ApiUrl + "/videos?uploadType=resumable&part=snippet&key=" + api.Tokens.ConsumerKey; // read for the different ways to interact with videos https://developers.google.com/youtube/v3/docs/#Videos
        var maxSize = 68719476736; // 64 gig

        try
        {
            var location = CompanyProvider.GetUploadLocation(this.baseUploadDirectory, companyId, FileType.Asset);
            var filePath = System.IO.Path.Combine(location, asset.FileName);
            using (var data = new FileStream(filePath, FileMode.Open))
            {
                if (maxSize > data.Length && (asset.MimeType.ToLower().StartsWith("video/") || asset.MimeType.ToLower().Equals("application/octet-stream")))
                {
                    var json = "{ \"snippet\": { \"title\": \"" + asset.FileName + "\", \"description\": \"This is a description of my video\" } }";
                    var buffer = Encoding.ASCII.GetBytes(json);

                    var request = WebRequest.Create(endPoint);
                    request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", api.Tokens.AccessToken);
                    request.Headers["X-Upload-Content-Length"] = data.Length.ToString();
                    request.Headers["X-Upload-Content-Type"] = asset.MimeType;
                    request.ContentType = "application/json; charset=UTF-8";
                    request.ContentLength = buffer.Length;
                    request.Method = "POST";

                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(buffer, 0, (int)buffer.Length);
                    }

                    var response = request.GetResponse();
                }
            }
        }
        catch (Exception ex)
        {
            eventLog.WriteEntry("Error uploading to youtube.\nEndpoint: " + endPoint + "\n" + ex.ToString(), EventLogEntryType.Error);
        }
    }

api.ApiUrl是https://www.googleapis.com/youtube/v3。我不确定是否需要密钥,它不会在文档中显示它,但我添加它以查看是否可以解决我的未授权问题。 另外,我认为如果没有密钥,它将如何知道要上传到哪个帐户?

任何人都可以看到我的代码出了什么问题吗?

非常感谢任何帮助。

更新1

经过一段时间排序后,我现在添加了一些代码,用于在尝试上传之前检查youtube凭据。这是通过以下代码完成的:

    public string GetAuthorizeApplicationUrl()
    {
        var sb = new StringBuilder();
        var dictionary = new Dictionary<string, string>
        {
            {"client_id", Tokens.ConsumerKey},
            {"redirect_uri", callbackUrl},
            {"response_type", "code"},
            {"scope", "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner"},
            {"approval_prompt", "force"},
            {"access_type", "offline"},
            {"state", ""}
        };

        sb.Append(requestTokenUrl);
        foreach (var parameter in dictionary)
        {
            var query = (sb.ToString().Contains("?")) ? "&" : "?";
            sb.Append(query + parameter.Key + "=" + parameter.Value);
        }

        return sb.ToString();
    }

这段代码负责构建允许我们要求用户访问的URL。

使用返回到返回URL的代码,我们称之为代码:

    public void RequestAccessToken(string code)
    {
        var dictionary = new Dictionary<string, string>
        {
            {"code", code},
            {"client_id", Tokens.ConsumerKey},
            {"client_secret", Tokens.ConsumerSecret},
            {"redirect_uri", callbackUrl},
            {"grant_type", "authorization_code"}
        };
        var parameters = NormalizeParameters(dictionary);

        var resultString = "";

        using (var wc = new WebClient())
        {
            //wc.Headers[HttpRequestHeader.Host] = "POST";
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            resultString = wc.UploadString(requestAccessTokenUrl, parameters);
        }

        var json = JObject.Parse(resultString);

        Tokens.AccessToken = json["access_token"].ToString();
        Tokens.RefreshToken = (json["refresh_token"] != null) ? json["refresh_token"].ToString() : null;
        Tokens.Save(companyId);
    }

现在因为我们已将我们的应用宣布为离线,当我们进行任何api调用时,我们可以使用这段代码:

    public bool CheckAccessToken()
    {
        try
        {
            RefreshToken(); // Get and store our new tokens

            return true;
        }
        catch
        {
            return false;
        }
    }

    private void RefreshToken()
    {
        var dictionary = new Dictionary<string, string>
        {
            {"refresh_token", Tokens.RefreshToken},
            {"client_id", Tokens.ConsumerKey},
            {"client_secret", Tokens.ConsumerSecret},
            {"grant_type", "refresh_token"}
        };
        var parameters = NormalizeParameters(dictionary);

        var resultString = "";

        using (var wc = new WebClient())
        {
            //wc.Headers[HttpRequestHeader.Host] = "POST";
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            resultString = wc.UploadString(requestAccessTokenUrl, parameters);
        }

        var json = JObject.Parse(resultString);

        Tokens.AccessToken = json["access_token"].ToString();
        Tokens.Save(companyId);
    }

在我的Windows服务中,我有这段代码:

    public void SynchroniseAssets(IEnumerable<SynchronisedAsset> assets)
    {
        if (api.CheckAccessToken())
        {
            foreach (var asset in assets)
            {
                var uploadAssetThread = new Thread(() => CreateUploadRequest(asset));
                uploadAssetThread.Start(); // Upload our assets at the same time
            }
        }
    }

您可以看到上面的原始代码。 我将它解析为json时得到的错误是:

{
   "error":{
      "errors":[
     {
        "domain":"youtube.header",
        "reason":"youtubeSignupRequired",
        "message":"Unauthorized",
        "locationType":"header",
        "location":"Authorization"
     }
      ],
      "code":401,
      "message":"Unauthorized"
   }
}

所以,如果有人能帮我弄清楚那意味着什么,那就太好了。

干杯,

/ r3plica

2 个答案:

答案 0 :(得分:7)

“youtubeSignupRequired”的原因通常表示YouTube帐户尚未正确设置,或者您尚未创建自己的YouTube频道。这是您上传视频之前的要求。 如果谷歌能够针对这种情况改进他们的错误信息并使其更加冗长,那就太好了。

答案 1 :(得分:4)

返回401 Unauthorized的问题是因为我获得访问权限的帐户没有与之关联的youtube帐户。