Search code examples
javascriptoauth-2.0discordfetch

Error redirect_uri: 'Not a well formed URL.' in discord OAuth2


I'm trying to do an OAuth2 for the discord, my code is this:

const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const querystring = require('querystring')

const router = express.Router();

const CLIENT_ID = '801791455034867723';
const CLIENT_SECRET = 'hehe :D, it\'s secret!';
const redirect = encodeURIComponent('http://localhost:50451/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://discordapp.com/api/oauth2/token`,
        {
            method: 'POST',
            headers: {
                Authorization: `Basic ${creds}`,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: querystring.stringify({
                grant_type: 'authorization_code',
                code: code,
                redirect_uri: redirect
            }),
        }
    );

    const json = await response.json();
    res.redirect(`/?token=${json.access_token}`);
}));

module.exports = router;

every time I run and give permission on the discord website, he gives this error: { redirect_uri: [ 'Not a well formed URL.' ] }.

where did I go wrong?


Solution

  • So your redirect variable is using the function "encodeURIComponent"

    const redirect = encodeURIComponent('http://localhost:50451/api/discord/callback');
    

    Try using a variable that is that callback string, but without that function call

    const redirect2 = 'http://localhost:50451/api/discord/callback'
    

    I actually was following the same Medium article as you! I think it was a bit outdated so the error occured.

    Then use redirect2 in your body

                body: querystring.stringify({
                  grant_type: 'authorization_code',
                  code: code,
                  redirect_uri: redirect
                }),