无需基于浏览器的oauth身份验证即可将文件从节点js传输到Dropbox

Jav*_*ans 17 node.js express dropbox-api

我正在从heroku运行一个基于nodejs + express的api服务器并使用dropbox-js库.这是我想做的事情:

  1. 用户点击特定的api端点并启动该过程.
  2. 通过节点进程生成一些文本文件并将其保存在服务器上
  3. 使用我自己的凭据(用户和Dropbox应用程序)将这些文件传输到我拥有的Dropbox.

当随机用户需要这样做时,永远不会出现这种情况.这是一个团队帐户,这是一个内部工具.

绊倒我的部分是dropbox想要打开浏览器窗口并获得我的许可以连接到应用程序.问题是,当进程在heroku实例上运行时,我显然无法单击该按钮.

有没有办法让我在节点中授权访问应用程序?

我觉得我可能会使用phantomJS进程点击按钮 - 但它看起来太复杂了,如果可能的话我想避免使用它.

这是我的验证码:

    // Libraries
    var Dropbox         = require('dropbox');

    var DROPBOX_APP_KEY    = "key";
    var DROPBOX_APP_SECRET = "secret";

    var dbClient = new Dropbox.Client({
      key: DROPBOX_APP_KEY, secret: DROPBOX_APP_SECRET, sandbox: false
    });

    dbClient.authDriver(new Dropbox.Drivers.NodeServer(8191));

    dbClient.authenticate(function(error, client) {
      if (error) {
        console.log("Some shit happened trying to authenticate with dropbox");
        console.log(error);
        return;
      }


      client.writeFile("test.txt", "sometext", function (error, stat) {
        if (error) {
          console.log(error);
          return;
        }

        console.log("file saved!");
        console.log(stat);
      });
    });
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 19

我做了一些测试,但这是可能的.

首先,您需要通过浏览器进行身份验证并保存Dropbox返回的令牌和令牌密钥:

dbClient.authenticate(function(error, client) {
  console.log('connected...');
  console.log('token ', client.oauth.token);       // THE_TOKEN
  console.log('secret', client.oauth.tokenSecret); // THE_TOKEN_SECRET
  ...
});
Run Code Online (Sandbox Code Playgroud)

获得令牌和秘密后,您可以在Dropbox.Client构造函数中使用它们:

var dbClient = new Dropbox.Client({
  key         : DROPBOX_APP_KEY,
  secret      : DROPBOX_APP_SECRET,
  sandbox     : false,
  token       : THE_TOKEN,
  tokenSecret : THE_TOKEN_SECRET
});
Run Code Online (Sandbox Code Playgroud)

在那之后,您不再需要通过浏览器进行身份验证(或者至少在某人没有令牌和秘密的情况下再次运行代码,这将使Dropbox生成新的令牌/密钥对并使旧的无效一个,或应用程序凭据被撤销).

  • 非常感谢你抽出时间来测试它!这正是我所寻找的.干杯! (2认同)
  • 我发现这个网站可以很容易地生成oauth2令牌,以便以这种方式使用:https://dbxoauth2.site44.com (2认同)

lon*_*ymo 9

或者您可以使用隐式授权并获取oauth令牌.

        var client = new Dropbox.Client({
            key: "xxxxx",
            secret: "xxxxx",
            token:"asssdsadadsadasdasdasdasdaddadadadsdsa", //got from implicit grant
            sandbox:false
        });
Run Code Online (Sandbox Code Playgroud)

根本不需要访问浏览器.不再需要此行!

   client.authDriver(new Dropbox.AuthDriver.NodeServer(8191));
Run Code Online (Sandbox Code Playgroud)