Skip to content

Instantly share code, notes, and snippets.

@182exe
Created April 11, 2024 05:10
Show Gist options
  • Save 182exe/60fb8b196004c2e3c9f66e86d4587024 to your computer and use it in GitHub Desktop.
Save 182exe/60fb8b196004c2e3c9f66e86d4587024 to your computer and use it in GitHub Desktop.
// thanks to gapple.pw for the very well made docs (https://mojang-api-docs.gapple.pw/)
// thanks to wiki.vg for teaching me microsoft auth scheme (https://wiki.vg/Microsoft_Authentication_Scheme)
const axios = require(`axios`)
async function getUsernameAndUUID(bearerToken) {
try {
const url = 'https://api.minecraftservices.com/minecraft/profile';
const config = {
headers: {
"Authorization": `Bearer ${bearerToken}`,
}
};
const response = await axios.get(url, config);
if (response.status !== 200) {
throw new Error(`Failed to retrieve data from the Minecraft API. Status code: ${response.status}`);
}
if (response.data.error === "NOT_FOUND") {
throw new Error(`Minecraft profile not found for the provided bearer token.`);
}
const { id, name } = response.data;
return {
uuid: id,
username: name
};
} catch (error) {
console.error('Error while fetching Minecraft profile: ', error.message);
return null;
}
}
// usage:
// const token = `eyJraWQiOiJhYzg0YSIsImFsZyI6IkhTMjU2In0.eyJ4dWlkIjoiMjUzNTQ...`
// const accountData = await getUsernameAndUUID(token)
//
// console.log(`uuid: ${accountData.uuid} | username: ${accountData.username}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment