首页 > 解决方案 > OAuth "unsupported_grant_type" Discord API

问题描述

我正在尝试使不和谐的 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()

谢谢你的帮助

标签: javascriptnode.jsoauthdiscord

解决方案


你的标题是:

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


推荐阅读