Authorization code grant flow

Hey y'all first time discord.js user. I'm using the latest version, going through the Authorization code grant flow in the guide. It's saying I should be returning
{
"access_token": "an access token",
"token_type": "Bearer",
"expires_in": 604800,
"refresh_token": "a refresh token",
"scope": "identify"
}
{
"access_token": "an access token",
"token_type": "Bearer",
"expires_in": 604800,
"refresh_token": "a refresh token",
"scope": "identify"
}
Except I don't get this back. My console is empty. I've tried changing response_type to code, and token, and neither of them return any information in my console. I'm not sure if i've missed a step but I've been staring at the guide for about an hour and a half to no avail. Here's my index.js just like the guide, for reference.
const { request } = require('undici');
const express = require('express');
const { clientId, clientSecret, port } = require('./config.json');

const app = express();

app.get('/', async ({ query }, response) => {
const { code } = query;

if (code) {
try {
const tokenResponseData = await request('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
code,
grant_type: 'authorization_code',
redirect_uri: `http://localhost:${port}`,
scope: 'identify',
}).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

const oauthData = await tokenResponseData.body.json();
console.log(oauthData);
} catch (error) {
// NOTE: An unauthorized token will not throw an error
// tokenResponseData.statusCode will be 401
console.error(error);
}
}

return response.sendFile('index.html', { root: '.' });
});



app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
const { request } = require('undici');
const express = require('express');
const { clientId, clientSecret, port } = require('./config.json');

const app = express();

app.get('/', async ({ query }, response) => {
const { code } = query;

if (code) {
try {
const tokenResponseData = await request('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
code,
grant_type: 'authorization_code',
redirect_uri: `http://localhost:${port}`,
scope: 'identify',
}).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

const oauthData = await tokenResponseData.body.json();
console.log(oauthData);
} catch (error) {
// NOTE: An unauthorized token will not throw an error
// tokenResponseData.statusCode will be 401
console.error(error);
}
}

return response.sendFile('index.html', { root: '.' });
});



app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
and my index.html
<!DOCTYPE html>
<html>
<head>
<title>My Discord OAuth2 App</title>
</head>
<div id="info">Hoi!</div>
<a
id="login"
style="display: none"
href="https://discord.com/api/oauth2/authorize?client_id=1128191375062605854&redirect_uri=http%3A%2F%2Flocalhost%3A53134&response_type=token&scope=identify"
>Identify Yourself</a
>
<script>
function generateRandomString() {
let randomString = "";
const randomNumber = Math.floor(Math.random() * 10);

for (let i = 0; i < 20 + randomNumber; i++) {
randomString = String.fromCharCode(33 + Math.floor(Math.random) * 94);
}
return randomString;
}

window.onload = () => {
const fragment = new URLSearchParams(window.location.hash.slice(1));
const [accessToken, toeknType, state] = [
fragment.get("access_token"),
fragment.get("token_type"),
fragment.get('state'),
];

if (!accessToken) {
const randomString = generateRandomString();
localStorage.setItem("oauth-state", randomString);

document.getElementById("login").href += `&state=${btoa(randomString)}`;
return (document.getElementById("login").style.display = "block");
}
if (localStorage.getItem('oauth-state') !== atob(decodeURIComponent(state))) {
return console.log("You may have been clickjacked!")
}
fetch("https://discord.com/api/users/@me", {
headers: {
authorization: `${toeknType} ${accessToken}`,
},
})
.then((result) => result.json())
.then((response) => {
const { username, discriminator } = response;
document.getElementById("info").innerText += ` ${username}`;
})
.catch(console.error);
};
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Discord OAuth2 App</title>
</head>
<div id="info">Hoi!</div>
<a
id="login"
style="display: none"
href="https://discord.com/api/oauth2/authorize?client_id=1128191375062605854&redirect_uri=http%3A%2F%2Flocalhost%3A53134&response_type=token&scope=identify"
>Identify Yourself</a
>
<script>
function generateRandomString() {
let randomString = "";
const randomNumber = Math.floor(Math.random() * 10);

for (let i = 0; i < 20 + randomNumber; i++) {
randomString = String.fromCharCode(33 + Math.floor(Math.random) * 94);
}
return randomString;
}

window.onload = () => {
const fragment = new URLSearchParams(window.location.hash.slice(1));
const [accessToken, toeknType, state] = [
fragment.get("access_token"),
fragment.get("token_type"),
fragment.get('state'),
];

if (!accessToken) {
const randomString = generateRandomString();
localStorage.setItem("oauth-state", randomString);

document.getElementById("login").href += `&state=${btoa(randomString)}`;
return (document.getElementById("login").style.display = "block");
}
if (localStorage.getItem('oauth-state') !== atob(decodeURIComponent(state))) {
return console.log("You may have been clickjacked!")
}
fetch("https://discord.com/api/users/@me", {
headers: {
authorization: `${toeknType} ${accessToken}`,
},
})
.then((result) => result.json())
.then((response) => {
const { username, discriminator } = response;
document.getElementById("info").innerText += ` ${username}`;
})
.catch(console.error);
};
</script>
</html>
8 Replies
d.js toolkit
d.js toolkit2y ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Javi
JaviOP2y ago
Well that’s for making bots right? All I’m trying to do is authorize users, not necessarily make a bot, it’s in a section of the discord.js so I thought I could come here for help
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Javi
JaviOP2y ago
Right that was my understanding of it, thanks for the clarification
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Javi
JaviOP2y ago
Thanks for the tip!
Want results from more Discord servers?
Add your server