-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
I mostly writing this so people who run into the problem I had will google this and see this request. I was using the Authorization Code Grant route and kept getting the errors 'invalid-client' and 'invalid-grant'. The reason why was because I was not sending properly formated form data, which I did not guess from the error messages given.
Solution: Use fetch or axiom, but make sure you set the body to a URL search param string or URLSearchParam object like below. If you do this, both will formate the search params into form data. The javascript FormData object is not implemented in nodejs and you should NOT make this post request from the client because it contains a plaintext version of your client secret.
const data = {
'client_id': process.env.DISCORD_BOT_CLIENT_ID,
'client_secret': process.env.DISCORD_BOT_CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': args.code,
'scope': 'identify connections gdm.join',
'redirect_uri': process.env.ROOT_URI + '/accounts/discord/landing',
}
const body = new URLSearchParams(data);
const discordResponse = await (await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body,
})).json()
I was using server-side fetch (via isomorphic-unfetch) to POST to that route and I had assumed that it would convert stringified JSON to form data when the Content-Type is set to 'application/x-www-form-urlencoded', but it does not. It will only convert URL search params.
How this could be made simpler? Just make this API route accept JSON data. We aren't posting any large files there no reason for this post to require form-data formate or add errors that specifically tell the user when they sent invalid form data instead of the vague errors that it sends right now.
How could we avoid the problem without changing the API? Just add a note to this section of the docs pointing out that this request needs to be made using form-data and not doing so could cause the 'invalid-client' and 'invalid-grant' errors. Even if people still run into this issue the note will make debugging much quicker.