【问题标题】:discord Oauth2 access token undefineddiscord Oauth2 访问令牌未定义
【发布时间】:2021-05-05 23:54:55
【问题描述】:

所以我正在尝试创建一个不和谐的机器人仪表板,并且我包括一个不和谐的 Oauth2 来获取用户信息。我的 Discord Oauth2 有效,但是在授权后,它将我重定向到主页,但 URL 有 token=undefined 。控制台确实记录“它有效!”。如何修复未定义的访问令牌?

http://localhost:3000/?token=undefined

var path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
require('dotenv').config();
const btoa = require('btoa');
const { catchAsync } = require('./utils.js')

const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('http://localhost:3000/callback');

...

app.get('/login', (req, res) => {
    res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20email%20guilds`);
  });

app.get('/callback', catchAsync(async (req, res) => {
    if (!req.query.code) throw new Error('NoCodeProvided');
    const code = req.query.code;
    const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
    const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
      {
        method: 'POST',
        headers: {
          Authorization: `Basic ${creds}`,
        },
      });
    const json = await response.json();
    console.log("it works!")
    res.redirect(`/?token=${json.access_token}`);
  }));
app.listen(3000)

【问题讨论】:

  • fetch 总是解析收到的任何数据,即使它是 404 或 500,为了检查是否有任何错误,您必须添加 if (!response.ok) { // log error... }。 AFAIK,/token 不允许 GET 查询,您是否尝试将数据放入正文?
  • @HoangDao 看来是发送请求的方式有问题,所以我改了格式,将CLIENT_ID、CLIENT_SECRET、redirect_uri、code等保存到变量中,作为URLSearchParams发送现在它可以工作了

标签: node.js express oauth-2.0 discord


【解决方案1】:

回调链接的设置方式似乎有问题,所以我将其更改为如下所示,并且可以正常工作。

app.get('/callback', catchAsync(async (req, res) => {

    const data = {
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        grant_type: 'authorization_code',
        redirect_uri: redirect,
        code: req.query.code,
        scope: ['identify', 'email', 'guilds'],
    };
    
    const response = await fetch('https://discord.com/api/oauth2/token', {
    method: 'POST',
    body: new URLSearchParams(data),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    })

    const json = await response.json();

    const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/@me', {
  headers: {
    Authorization: `Bearer ${json.access_token}`,
  }
});
const userInfo = await fetchDiscordUserInfo.json();

    res.redirect('http://localhost:3000/dashboard')

console.log(userInfo);

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2018-07-17
    • 2019-12-24
    • 2013-09-25
    • 2011-03-07
    • 2016-07-07
    • 2016-03-05
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多