Discord oauth API inavlid_reuqest error. - express.js

Viewed 334

I have created multiple website using this tutorial https://medium.com/@orels1/using-discord-oauth2-a-simple-guide-and-an-example-nodejs-app-71a9e032770 and they all worked perfectly until yesterday. The problem is that when a user authenticates and goes to https://mywebsite.com/api/discord/callback?code={discord response code} the api gets an error when trying to convert the code with a access_token. This is the code for my discord api callback:


const router = express.Router();

const fetch = require('node-fetch');
const FormData = require('form-data');

const btoa = require('btoa');
const { catchAsync } = require(__dirname+'/utils');

const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('https://mywebsite.com/api/discord/callback');

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

router.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://discord.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(json)
  res.redirect(`/finallogin/?token=${json.access_token}`);
}));

module.exports = router;

When a user authenticates, he gets redirected to https://mywebsite.com/finallogin/?token=undefined and I'm getting this error on console:

  error: 'invalid_request',
  error_description: 'Missing "code" in request.'
}

This was working perfectly before and just randomly broke a few days ago on all of my websites. Any help / solution / idea will be appreciated.

(Note: the "https://mywebsite.com" is just an example and not my actual website url)

Thanks, RealPower2Maps.

0 Answers
Related