javascript - 如何将访问 token 从 .NET(代码隐藏)传递到 Javascript

标签 javascript c# .net youtube-api google-api-dotnet-client

我想使用我自己的 API key 、 key 和刷新 token 通过 .NET 框架进行“授权”,然后将访问 token 传递给 JavaScript,以便我可以将视频直接上传到 YouTube带有进度指示器。

我有working code via the .NET API这将完成直接上传到我的 channel [未经授权],但您不会得到任何进度指示(并且可能需要相当长的时间),并且文件必须首先上传到我的服务器,然后再上传到 YouTube 服务器。

服务器端访问代码与客户端访问代码不同吗?如果没有:

  1. 服务器端如何获取访问码?(获取字符串)
  2. ***我如何通过 JavaScript 将其传递给 Google API? (不是如何写 <%= access code %> 而是将其传递到哪里?)

我很清楚暴露访问 token 的安全风险,但是这些 token 确实会过期,对吗? (作为奖励,我怎样才能缩短过期时间)。这也是在受密码保护的网页内完成的,并且您不会获得“客户端 key ”或“刷新 token ”

***更新 - 我想我找到了传递 token 的位置,在 MediaUploader 中对象。

var uploader = new MediaUploader({
        baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
        file: selectedFile,
        token: token, // ***RIGHT HERE***
        metadata: metadata,
        params: params,
        onError: function(data) {

最佳答案

好吧,经过几周的研究 API、.NET 和 JavaScript 文档,我构建了以下解决方案......

根据 YouTube V3 Developer documentation设置好您的 key 。 (选择 OAuth、Web 应用程序,然后输入 Javascript 和重定向代码的 URI)

接下来使用OAuth Playground获取您的刷新代码

一旦您获得了 client_id、client_secret 和 refresh_token,您就可以开始使用了!

此代码通过后面的代码进行简单的 HTTP/REST 调用,以获取有效时间为 3600 秒(默认值)的 access_token。然后它将此字符串传递给 JavaScript 代码以供使用****警告****

除了一个文件 cors_upload.js available on GitHub 之外,此使用任何 .NET 或 JavaScript 库。

阿拉斯,代码
默认.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ApisCallTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta charset="utf-8" />
    <title>YouTube API Uploads via CORS</title>
    <style>
      #disclaimer {
        font-size: 0.75em;
        color: #aeaeae;
        max-width: 350px;
      }
      .during-upload { display: none; }
      label { display: block; }
      input[type="text"],
      textarea,
      progress {
        font-size: 16px;
        width: 15em;
        margin-bottom: 1em;
        padding: 0.5em;
        font-family: "Open Sans", sans-serif;
      }
    </style>
</head>
  <body>
    <div>
    <input input type="file" id="file" class="button" accept="video/*" />
    <button id="button">Upload Video</button>
    </div>
    <div class="during-upload">
    <p><span id="percent-transferred"></span>% done (<span id="bytes-transferred"></span>/<span id="total-bytes"></span> bytes)</p>
    <progress id="upload-progress" max="1" value="0"></progress>
    </div>
    <p id="disclaimer">By uploading a video, you certify that you own all rights to the content or that you are authorized by the owner to make the content publicly available on YouTube, and that it otherwise complies with the YouTube Terms of Service located at <a href="http://www.youtube.com/t/terms" target="_blank">http://www.youtube.com/t/terms</a></p>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="cors_upload.js"></script>
    <script>
      $('#button').on("click", goForUpload);
      function goForUpload() {
        if ($('#file').get(0).files[0]) {
          $('#button').attr('disabled', true);
          var uploadStartTime = 0;
          var metadata = {
            snippet: {
              title: 'PUT YOU TITLE HERE',
              description: 'THIS IS YOUR VIDEO DESCRIPTION',
              categoryId: '22'
            },
            status: {
              privacyStatus: 'unlisted'
            }
          };

          var uploader = new MediaUploader({
            baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
            file: $('#file').get(0).files[0],
            token: '<%= access_token %>',
            metadata: metadata,
            params: {
              part: Object.keys(metadata).join(',')
            },
            onError: function (data) {
              var message = data;
              // Assuming the error is raised by the YouTube API, data will be
              // a JSON string with error.message set. That may not be the
              // only time onError will be raised, though.
              try {
                var errorResponse = JSON.parse(data);
                message = errorResponse.error.message;
              } finally {
                alert(message);
              }
            },
            onProgress: function (data) {
              var currentTime = Date.now();
              var bytesUploaded = data.loaded;
              var totalBytes = data.total;
              // The times are in millis, so we need to divide by 1000 to get seconds.
              var bytesPerSecond = bytesUploaded / ((currentTime - this.uploadStartTime) / 1000);
              var estimatedSecondsRemaining = (totalBytes - bytesUploaded) / bytesPerSecond;
              var percentageComplete = (bytesUploaded * 100) / totalBytes;

              $('#upload-progress').attr({
                value: bytesUploaded,
                max: totalBytes
              });

              $('#percent-transferred').text(percentageComplete);
              $('#bytes-transferred').text(bytesUploaded);
              $('#total-bytes').text(totalBytes);

              $('.during-upload').show();
            },
            onComplete: function (data) {
              var uploadResponse = JSON.parse(data);
              alert('all done, you can store this id: ' + uploadResponse.id)
            }
          });
          uploadStartTime = Date.now();
          uploader.upload();
        }
      }
    </script>
  </body>
</html>

和Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace ApisCallTest
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private static readonly HttpClient client = new HttpClient();
        public string access_token;
        protected void Page_Load(object sender, EventArgs e)
        {
            var values = new Dictionary<string, string>
            {
               { "client_id", "REPLACE_ME" },
               { "client_secret", "REPLACE_ME" },
               { "refresh_token", "REPLACE_ME" },
               { "grant_type", "refresh_token" }
            };

            var content = new FormUrlEncodedContent(values);
            var response = client.PostAsync("https://www.googleapis.com/oauth2/v4/token", content);
            string json = response.Result.Content.ReadAsStringAsync().Result;
            dynamic obj = JObject.Parse(json);
            access_token = obj.access_token;
        }
    }
}

结果...从受密码保护的网页,我可以让用户将视频上传到我的 channel (不公开),并存储视频 ID,以便稍后将该视频嵌入回我的网站。

至于****警告****,这在某种程度上是一个安全问题,因为您将(非常直接)您的个人访问 key 暴露给“公众”。它只持续 1 小时,但将您使用的任何访问“范围”提供给“任何人”。尝试在某种程度上混淆 key 是个好主意,至少不要在公开场合这样做可用页面。

关于javascript - 如何将访问 token 从 .NET(代码隐藏)传递到 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49455645/

相关文章:

javascript - 有没有一种简单的方法可以用简单的英语来理解 JavaScript 的 .bind ?

javascript - jQuery : Remove created element if CLICKED button value is xxx

c# - 如何首先使用迁移向 Entity Framework 4.3 代码中的列添加描述?

c# - 如何在没有setter的情况下实现INotifyPropertyChanged?

c# - 如何知道静态方法的类名

c# - Dapper:ConnectionString 属性尚未初始化

javascript - react : Resizing a div including handlers, 不同的游标,即 ns-resize - 没有 jquery

javascript - 向左滑动时弹出右侧div而不是平滑滑动

c# - 如何通过 cellFormatting Telerik 覆盖单元格颜色

.net - 如何在 Azure 部署的应用程序中应用数据库代码优先迁移?