Home > Software design >  Discord OAUTH2 with node.js
Discord OAUTH2 with node.js

Time:01-02

I need discord OAUTH2 login system but i dont know how. I was trying something but it shows me "loginned" again when im not loginned.

i was trying this but i dont know how to do that, if im not loginned that it shows me im not loginned.

const express = require("express")
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
const app = express()

var config = {
  "clientId": process.env["CLIENT_ID"],
  "clientSecret": process.env['CLIENT_SECRET'],
  "redirectUri": "redirect uri"
}

app.get("/", (request, response) => {
  response.send("login with discord: <a href='redirect url'>login</a>")
})

app.get("/authorize", (request, response) => {
  var code = request.query["code"]
  var params = new URLSearchParams()
  params.append("client_id", config["clientId"])
  params.append("client_secret", config["clientSecret"])
  params.append("grant_type", "authorization_code")
  params.append("code", code)
  params.append("redirect_uri", config["redirectUri"])
  fetch(`https://discord.com/api/oauth2/token`, {
    method: "POST",
    body: params
  })
  .then(res => res.json())
  .then(json => {
    response.send("logged in")
  })
})

app.listen(80, () => {
  console.log("Listening on :80")
})

CodePudding user response:

Using axis with POST call. It makes life easier.

#1 Setup my App at enter image description here

#2 Setup OAuth2 at discord developer portal

Add Redirects, Copy Client and Client Secret And give administrator permission (for test purpose)

![enter image description here

#3 Save config.json with Client ID/Secret and Redirects URI

It will use demo.js for get Token API call.

{
    "CLIENT_ID" : "********** your  Client ID *********",
    "CLIENT_SECRET" : "********** your  Client Secret *********",
    "REDIRECT_URI" : "http://localhost:3000/api/callback" <- this should be matched your REDIRECT_URI of Developer Portal
}

#4 Express App Server with demo.js file name.

const express = require("express")
const axios = require('axios')
const config = require('./config.json');

const app = express()

app.get("/login", (request, response) => {
    const redirect_url = `https://discord.com/oauth2/authorize?response_type=code&client_id=${config.CLIENT_ID}&scope=identify&state=123456&redirect_uri=${config.REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url);
})

app.get("/api/callback", async (request, response) => {
    const code = request.query["code"]
    const resp = await axios.post('https://discord.com/api/oauth2/token',
        new URLSearchParams({
            'client_id': config.CLIENT_ID,
            'client_secret': config.CLIENT_SECRET,
            'grant_type': 'authorization_code',
            'redirect_uri': config.REDIRECT_URI,
            'code': code
        }),
        {
            headers:
            {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
    response.send('Logged In: '   JSON.stringify(resp.data));
})

app.listen(3000, () => {
    console.log("Listening on :3000")
})

#5 Install dependencies and run it

$ npm install express axios
$ node demo.js
Listening on :3000

#6 Access Login page by Chrome

http://localhost:3000/login

It will be forward to discord login page. If shows this screen, press `A button.

enter image description here

Back to call my express URL then display access token and logged in message.

enter image description here

Returned Result this JSON format.

{
    "access_token": "*****************************",
    "expires_in": 604800,
    "refresh_token": "*****************************",
    "scope": "identify",
    "token_type": "Bearer"
}

CodePudding user response:

The code above is almost done, but that is not store an authorization data that use to get user info. You need to make another request to the Discord API to get user info. install axios and add the code below

axios.get("https://discord.com/api/users/@me", make_config(data.access_token)).then(response => {
  res.status(200).send(response.data.username);
 }).catch(err => {
  console.log(err);
  res.sendStatus(500);
});
  • Related