簡體   English   中英

Discord OAUTH2 與 node.js

[英]Discord OAUTH2 with node.js

我需要 discord OAUTH2 登錄系統,但我不知道怎么做。 我正在嘗試一些事情,但是當我沒有登錄時它再次顯示我“已登錄”。

我正在嘗試這個,但我不知道該怎么做,如果我沒有登錄,它會顯示我沒有登錄。

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")
})

通過 POST 調用使用軸。 它讓生活更輕松。

#1 在discord 開發者門戶設置我的應用程序

在此處輸入圖像描述

#2 在 discord 開發者門戶設置 OAuth2

添加重定向、復制客戶端和客戶端密碼並授予管理員權限(用於測試目的)

![在此處輸入圖片描述

#3 使用客戶端 ID/密碼和重定向 URI 保存config.json

它將使用demo.js獲取令牌 API 調用。

{
    "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 具有demo.js文件名的 Express App Server。

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 安裝依賴並運行它

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

#6 通過 Chrome 訪問登錄頁面

http://localhost:3000/login

它將轉發到 discord 登錄頁面。 如果顯示此屏幕,請按`一個 按鈕。

在此處輸入圖像描述

返回呼叫我的快遞 URL,然后顯示訪問令牌和登錄消息。

在此處輸入圖像描述

返回結果為 JSON 格式。

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

上面的代碼差不多完成了,但是它沒有存儲用於獲取用戶信息的授權數據。 您需要向 Discord API 再次請求以獲取用戶信息。 安裝 axios 並添加下面的代碼

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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM