【发布时间】:2018-09-09 15:40:23
【问题描述】:
我目前已经走进了 OAuth2 的世界,并且对它有一些的了解。我正在尝试制作一个应用程序,您可以在其中授权 Discord 帐户并让它自动邀请您加入公会/服务器。
我在 Nginx 代理后面使用 Express Web 服务器,该代理已经配置好并且工作起来就像一个魅力。我使用名为“request”的 Node.JS 依赖项向 Discord 服务器发出 post 请求。
当我允许应用程序 (Discord Callback) 时,以下代码将处理来自 Discord 的回调。回调将在 GET 查询中包含一个代码,该代码将被转发到 Discord 令牌 URL 以接收访问令牌。此访问令牌允许应用程序对用户帐户执行操作,事实是,它不起作用,我将在下面解释。 :-)
// there would be another variable here named 'state'
// which essentially is another security feature but this
// definitely works. The state gets calledback from the
// discord authorisation which is a hashed cookie
var clientId = '123' // Discord client ID (string to not lose accuracy)
var clientSecret = 'secretsauce' // Discord secret key
var code = req.query.code // received on router event (express)
var discordTokenURL = 'https://discordapp.com/api/oauth2/token'
var redirectUri = 'https://myapp.com/callback/discord' // redirect for when I allow my app to look at my data, or even when I refuse it
// dependency to make request
var request = require('request')
// post the data to the discord server
request.post({
url: discordTokenURL,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: { grant_type: 'authorization_code', client_id: clientId, client_secret: clientSecret, code: code, redirect_uri: redirectUri }
},
function (err, httpResponse, body) {
if (err) {
return console.error('server down or other error') // only errors when Discord server is down
}
res.send(body) // returns the server response ({"error": "access_denied"})
})
代码成功执行,没有任何错误。在 Discord OAuth2 文档中,我应该会收到这样的回复:
{
"access_token": "6qrZcUqja7812RVdnEKjpzOL4CvHBFG",
"token_type": "Bearer",
"expires_in": 604800,
"refresh_token": "D43f5y0ahjqew82jZ4NViEr2YafMKhue",
"scope": "identify"
}
不幸的是,我得到了一个看起来像这样的可爱的:
{"error": "access_denied"}
任何帮助将不胜感激,我查看了很多文章并阅读了很多次 API 文档,但没有任何问题得到解决。我发现如果我将“grant_type”设置为“client_credentials”,它确实会返回一个有效的响应,这肯定证实了我最初认为我的服务器被 IP 禁止 Discord 的想法是不正确的。不幸的是,“client_credentials”不能满足我的目的,我需要“authorization_code”。
谢谢。 :-)
【问题讨论】:
标签: node.js express oauth oauth-2.0 discord