通过 request.js 从代码中获取 Dropbox OAuth 令牌失败;等效的卷曲作品

Get Dropbox OAuth Token from Code via request.js Fails; Equivalent curl Works

我正在尝试根据 http api 文档将我的 Dropbox oauth 代码交换为令牌。

当我这样用curl执行命令时:

curl https://api.dropbox.com/1/oauth2/token \
-d code=<authorization code> \
-d grant_type=authorization_code \
-u <app key>:<app secret>

一切正常,我的不记名令牌已返回。不幸的是,什么 似乎是用 node.js 编写的等效代码,请求模块失败。

var request = require("request");
var config = require("./config.json");

request({
  url: "https://api.dropboxapi.com/1/oauth2/token",
  method: "POST",
  auth: {
    user: config.client_id,
    pass: config.client_secret
  },
  json: {
    code: config.code,
    grant_type: "authorization_code"
  } 
}, function(err, resp, body) {
  if (err) throw err;
  console.log(body);
});

日志:

{ error_description: 'missing required field "grant_type"',
  error: 'invalid_request' }

The docs 说如果出现 400 错误(这是错误),我有:

Bad input parameter. Error message should indicate which one and why.

虽然从上面的代码可以看出,grant_type 指定。


值得注意的是,文档提供了第二种身份验证选项,尽管这也失败了, 尽管有不同的信息:

Description (abridged)

Calls to /oauth2/token need to be authenticated using the apps's key and secret. These can either be passed as POST parameters (see parameters below) or via HTTP basic authentication. If basic authentication is used, the app key should be provided as the username, and the app secret should be provided as the password.

Params

  • code String The code acquired by directing users to /oauth2/authorize?response_type=code.
  • grant_type String The grant type, which must be authorization_code.
  • client_id String If credentials are passed in POST parameters, this parameter should be present and should be the app's key (found in the App Console).
  • client_secret String If credentials are passed in POST parameters, this parameter should be present and should be the app's secret.
  • redirect_uri String Only used to validate that it matches the original /oauth2/authorize, not used to redirect again.

我对备用身份验证过程的尝试:

var request = require("request");
var config = require("./config.json");

request({
  url: "https://api.dropboxapi.com/1/oauth2/token",
  method: "POST",
  json: {
    code: config.code,
    grant_type: "authorization_code",
    client_id: config.client_id,
    client_secret: config.client_secret
  } 
}, function(err, resp, body) {
  if (err) throw err;
  console.log(body);
});

日志:

{ error_description: 'No auth function available for given request',
  error: 'invalid_request' }

如果 dropbox 对我的两次请求尝试中的任何一次的完整响应会有所帮助 I posted it on pastebin

我不包括 redirect_uri 因为我没有将它用作代码的一部分 流动。根据文档,这是允许的。无论如何,我没有任何问题 在 curl 命令中省略它时 确实 成功。

考虑到我的 API 调用在通过 curl 发送时成功,我显然在做 我的 js 请求有问题。我该怎么做才能获得不记名令牌 期待?

看起来在您的 curl 命令中,您正在发送 form-encoded POST 请求(这是 OAuth 使用的),但在您的 Node.js 代码中,您正在发送 JSON-encoded 请求。

尝试 form: { ... } 而不是 json: { ... }