简体   繁体   English

Discord OAUTH2 与 node.js

[英]Discord OAUTH2 with node.js

I need discord OAUTH2 login system but i dont know how.我需要 discord OAUTH2 登录系统,但我不知道怎么做。 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")
})

Using axis with POST call.通过 POST 调用使用轴。 It makes life easier.它让生活更轻松。

#1 Setup my App at discord developer portal #1 在discord 开发者门户设置我的应用程序

在此处输入图像描述

#2 Setup OAuth2 at discord developer portal #2 在 discord 开发者门户设置 OAuth2

Add Redirects, Copy Client and Client Secret And give administrator permission (for test purpose)添加重定向、复制客户端和客户端密码并授予管理员权限(用于测试目的)

![在此处输入图片描述

#3 Save config.json with Client ID/Secret and Redirects URI #3 使用客户端 ID/密码和重定向 URI 保存config.json

It will use demo.js for get Token API call.它将使用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 Express App Server with demo.js file name. #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 Install dependencies and run it #5 安装依赖并运行它

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

#6 Access Login page by Chrome #6 通过 Chrome 访问登录页面

http://localhost:3000/login

It will be forward to discord login page.它将转发到 discord 登录页面。 If shows this screen, press如果显示此屏幕,请按`一个 button.按钮。

在此处输入图像描述

Back to call my express URL then display access token and logged in message.返回呼叫我的快递 URL,然后显示访问令牌和登录消息。

在此处输入图像描述

Returned Result this JSON format.返回结果为 JSON 格式。

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

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.您需要向 Discord API 再次请求以获取用户信息。 install axios and add the code below安装 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.

相关问题 从Node.js / Javascript连接到OAuth2 API时出现问题? - Issues connecting to OAuth2 API from Node.js/Javascript? 如何在Node.js中发现Google OAuth2中的API - How to discover APIs in Google OAuth2 in Node.js 在 discord js 中提供 OAuth2 不记名令牌 - Provide OAuth2 bearer token in discord js Discord guilds.join OAuth2 in JS - Discord guilds.join OAuth2 in JS 基于Angular.js + Node.js / PassportJS的SPA上的oauth2 auth - oauth2 auth on SPA based on Angular.js + Node.js/PassportJS 有人可以使用 ELI5 如何使用 node.js 正确执行离线 Google oauth2 吗? - Can someone ELI5 how to properly do offline Google oauth2 with node.js? ExpressJS Node.js Angular 错误:getaddrinfo ENOTFOUND 在获取 OAuth2 API 授权令牌时 - ExpressJS Node.js Angular Error: getaddrinfo ENOTFOUND While Getting OAuth2 API Authorisation Token 从node.js oauth2服务器到服务器客户端(谷歌跟踪身份验证) - node.js oauth2 server to server client (google tracks authentication) OAuth2授权代码授予流Node.js与客户端混合 - OAuth2 Authorization Code Grant Flow Node.js mixed with Client-Side 是否有任何Node.js客户端库可以对Twitter,Facebook,Google,LinkedIn等进行OAuth和OAuth2 API调用? - Is there any Node.js client library to make OAuth and OAuth2 API calls to Twitter, Facebook, Google, LinkedIn, etc.?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM