I am trying to implement a Discord-Login onto my Website. Unfortunately I am getting an error from discord.
Does anybody see, whats wrong with my code?
FYI: I am already get back the code from discord. So my first request is working fine.
What I want to do with the Data:
I want to get the user_ID so I can add groups to the user on my Discord Server.
ERROR:
error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'
Code:
router.get('/account-settings/connections/discord/callback', (async (req, res) => {
const code = await req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
fetch(`https://discordapp.com/api/oauth2/token`, {
method: "POST",
headers: {
Authorization: `Basic ${creds}`,
},
body: querystring.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: dis_redirect
}),
})
.then((res) => res.json())
.then((body) => console.log(body));
})
Thank you very much in advance!!!
The best regards, Joshy
Okay for everybody else, who has this problem. I was able to fix this with parsing all information in the body and setting up the content type in the headers. Here is a working code:
let params = new URLSearchParams();
params.append('client_id', CLIENT_ID);
params.append('client_secret', CLIENT_SECRET);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', dis_redirect);
fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
}).then(r => r.json()).then(async Response => {
In the code variable, I have stored the request query, I am getting back from TwithOauth (After autorization of the user). Client ID and Client Secret you will get from your Discord Application. The dis_redirect virable is containing my redirection link, which is just blank string of my Link, I have setup to get the router.
Nothing more is needed.
You will get a JSON responded, which you can work with. If you want to get the users data (like me) this following code is what you searching for:
let refresh_token = Response.refresh_token;
let accessToken = Response.access_token;
var site = await fetch("https://discord.com/api/v9/users/@me", {
method: 'GET',
headers: {'Authorization': `Bearer ${accessToken}`}
});
var response = await site.json();
console.log(response);
});
This code you will place directly in the new opened async function. There you have it. All users data, you will need.
I hope I was able to help someone. If you have any questions, just let me know!
The best regards, Joshy