【问题标题】:Unsupported grant type when getting OAuth token for Reddit API获取 Reddit API 的 OAuth 令牌时不支持的授权类型
【发布时间】:2018-09-18 02:33:14
【问题描述】:

我正在尝试在Application Only OAuth instructions 之后为 Reddit API 获取 OAuth 令牌。我的 reddit 应用程序是已安装的应用程序,所以对于我的 grant_type,我使用的是 https://oauth.reddit.com/grants/installed_client

目前我正在运行一个非常短的 JS 脚本来查询 API 并获取令牌:

const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'


let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)

fetch('https://www.reddit.com/api/v1/access_token', {
   method: 'POST',
   headers: new Headers({
     'Content-Type': 'application/x-www-form-urlencoded',
     'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
   }),
   body: form })
  .then(handleResponse)
  .then(function(data) {
console.log(data)
  })
  .catch(error => console.error(error))

function handleResponse(response) {
  return response.json()
}

(注意:按原样运行 sn-p 会给您一个 NetworkError,因为 APP_ID 不是真实的,我不想给出我的。)

我得到的回应是:

{
  "error": "unsupported_grant_type"
}

当我使用 REST 客户端尝试相同的 API 请求时,我得到了预期的响应,所以这让我认为问题与 JavaScript 相关。由于grant_type 与说明中的内容相匹配,因此我不确定如何处理该错误。我希望其他对 OAuth 更有经验的人会知道这里发生了什么。

【问题讨论】:

    标签: javascript api oauth-2.0 reddit


    【解决方案1】:

    问题在于FormData 对象的使用。在故障排除的早期阶段,我在 Reddit 上找到了 this answer 并决定使用它,但这对我不起作用。

    它以multipart/form-data 而不是application/x-www-form-urlencoded 提交数据,这是Reddit 的OAuth 服务器不喜欢的。我写了一个基于this answer 的辅助函数,它成功了:

    function urlEncode(data) {
      let out = [];
    
      for (let key in data) {
        out.push(`${key}=${encodeURIComponent(data[key])}`);
      }
    
      return out.join('&')
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 2021-01-08
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多