如何将访问令牌从.NET(代码隐藏)传递给Javascript [英] How to pass an Access Token from .NET (code behind) to Javascript

查看:102
本文介绍了如何将访问令牌从.NET(代码隐藏)传递给Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过.NET框架授权使用我自己的API密钥,秘密和刷新令牌,然后将访问令牌传递给JavaScript,以便我可以直接将视频上传到YouTube有进度指示器。

I would like to "authorize" via the .NET framework using my own API keys, secret and Refresh Token, and then pass the Access Token to JavaScript so I can upload a video directly to YouTube with a progress indicator.

我有通过.NET API工作代码,可以直接上传到我的频道[未经授权],但是你没有进度指示(它可以需要一段时间)文件必须首先上传到我的服务器,然后上传到YouTube服务器。

I have working code via the .NET API that will accomplish the upload directly to my channel [without authorization], but you get no progress indication (and it can take quite some time) and the file must be uploaded to my server first, then to YouTube server.

服务器端访问代码是否与客户端访问代码不同?如果不是:

Is a server side access code different from a client side access code? If not:


  1. 如何获取访问代码服务器端?(获取字符串)

  2. ***如何通过JavaScript将其传递给Google API? (不是如何写<%=访问代码%> 但在哪里传递?)

  1. How can I obtain the access code server side? (get the string)
  2. ***How can I pass it to Google APIs via JavaScript? (not how to write <%= access code %> but where to pass it in?)

我很清楚暴露访问令牌的安全风险,但这些确实会过期吗? (作为奖励,我如何缩短过期时间)。这也是在受密码保护的网页内完成的,你没有得到'客户机密码'或'刷新令牌'

I am well aware of the security risk in exposing the access token, but these do expire right? (as a bonus, how can I shorten the expire time). This is also being done inside a password protected web page, and you don't get the 'client secret' or 'refresh token'

***更新 - 我认为我在 MediaUploader 对象中找到了传递令牌的位置。

***update - I think I found where to pass in the token, in the MediaUploader object.

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文档,我已经构建了以下内容解决方案....

Okay, so after weeks of smashing my way through the APIs, .NET, and JavaScript documentation I have built the following solution....

根据 YouTube V3开发人员文档让您的密钥全部设置完毕。(选择OAuth,Web应用程序,然后输入U.您的Javascript和重定向代码的RI)

As per the YouTube V3 Developer documentation get your Keys all set up. (choose OAuth, Web Application, and enter URIs for both your Javascript and Redirect code)

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

Next use the OAuth Playground to obtain your Refresh Code

一旦有了client_id,client_secret和refresh_token,您就可以摇滚了!

Once you have your client_id, client_secret, and refresh_token you are ready to rock!

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

This code makes a simple HTTP/REST call via the code behind to obtain an access_token which is good for 3600 seconds (the default). It then passes this string to the JavaScript code for use ****WARNING****

使用任何一个。除一个文件外的.NET或JavaScript库,cors_upload.js 在GitHub上可用

This does not use any of the .NET or JavaScript Libraries with the exception of one file, the cors_upload.js available on GitHub

Allas,代码

Default.aspx

Allas, the code
Default.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

and 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;
        }
    }
}

结果......来自受密码保护的网页我可以让用户将视频上传到我的频道,不公开,并存储视频ID,以便稍后将该视频重新嵌入我的网站。

The result... From a password protected web page I can have a user upload a video to MY channel, unlisted, and store the video ID to later embed that video back on my website.

as对于****警告****,这是一个安全问题,因为您(非常直接地)将您的个人访问密钥暴露给公共。它只持续1小时,但是给你任何人使用的任何访问范围。尝试在某种程度上破坏密钥是一个好主意,至少,不要公开这样做可用页面。

as for the ****WARNING****, this is somewhat of a security concern as you are exposing (very directly) your PERSONAL access key to the "public". It only lasts for 1 hour, but gives whatever "scope" of access you are using to "anyone" It would be a good idea to try and obstuficate the key somewhat, and at the very least, don't do this on a publicly available page.

这篇关于如何将访问令牌从.NET(代码隐藏)传递给Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆