OAuth“ unsupported_grant_type” Discord API

时间:2018-11-19 18:44:06

标签: javascript node.js oauth discord

我正在尝试使不一致的OAuth正常工作。在文档中,有必要生成一个代码,此步骤非常有效,但是要生成令牌。它要求使用正确的参数发出POST请求,但总是给我带来错误:{"error":"unsupported_grant_type"}

我的代码:

app.get('/discord/callback', async function (req, res) {
    if (req.query.code === undefined || req.query.code == '') return next();

    const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
        method: 'POST',
        headers: {
            "Content-type": "application/x-www-form-urlencoded"
        },
        data: {
            client_id: process.env.CLIENT_ID,
            client_secret: process.env.CLIENT_SECRET,
            code: req.query.code,
            redirect_uri: redirect,
            grant_type: "authorization_code",
            scope: "identify"
        }
    });
    const json = await response.json();

    debug('%O', json);
    res.send(json);
});

文档:

def exchange_code(code):
  data = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': REDIRECT_URI,
    'scope': 'identify email connections'
  }
  headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  r = requests.post('%s/oauth2/token' % API_ENDPOINT, data, headers)
  r.raise_for_status()
  return r.json()

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您的标题是:

headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }

这意味着它也期望数据作为表单数据而不是 json。

所以这应该有效:

    app.get('/discord/callback', async function (req, res) {
      if (req.query.code === undefined || req.query.code == '') return next();

      const params = new URLSearchParams();
      params.append('client_id', process.env.CLIENT_ID);
      params.append('client_secret', process.env.CLIENT_SECRET);
      params.append('grant_type', 'authorization_code');
      params.append('code', code);
      params.append('redirect_uri', redirect);
      params.append('scope', 'identify');

      const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
        method: 'POST',
        body: params
        headers: {
            "Content-type": "application/x-www-form-urlencoded"
        },
      });
     const json = await response.json();

     debug('%O', json);
     res.send(json);
 });

您可以参考这个以更好地理解:https://www.npmjs.com/package/node-fetch#post-with-form-parameters

答案 1 :(得分:0)

我今天也遇到了这个问题,在 Aakash Sharma 的回答的启发下,我构建了一个小实用函数(在打字稿中),它将对象转换为所需的格式:

public getCoinList()