[英]OAuth2: Discord API always responds with {“error”: “invalid_grant”}
I am trying to implement Discord OAuth2 in my node.js Application.我正在尝试在我的 node.js 应用程序中实现 Discord OAuth2。 As soon as I try to get the access token from the given authorization code, I always get the HTTP response Error 400 {"error": "invalid_grant"}
一旦我尝试从给定的授权码中获取访问令牌,我总是得到 HTTP 响应错误 400 {“error”:“invalid_grant”}
let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://discord.com/api/oauth2/token')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
let payload ={
client_id: clientID,
client_secret: clientSecret,
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUrl,
scope: 'identify'
};
console.log(payload)
xhr.send(JSON.stringify(payload))
xhr.onreadystatechange = () => {
console.log(xhr.status)
console.log(xhr.responseText)
}
xhr.onerror = () => {
console.log('Failed')
}
Okay I solved the issue.好的,我解决了这个问题。 For everyone who is experiencing the same issue that I had, I solved it by using axios and querystring to send the POST request to the Discord API ( https://github.com/discord/discord-api-docs/issues/1131 )
For everyone who is experiencing the same issue that I had, I solved it by using axios and querystring to send the POST request to the Discord API ( https://github.com/discord/discord-api-docs/issues/1131 )
It seems that there is a problem with the JSON and the x-www-form-urlencoded format. JSON 和 x-www-form-urlencoded 格式似乎有问题。
I had the same issue when trying to use on Next.js's GetServerSideProps function.尝试在Next.js 的 GetServerSideProps function 上使用时,我遇到了同样的问题。
After searching a lot, I found an closed issue on Github solving this problem ( Github Issue: Deep Linking with OAuth2 Not Working ).经过大量搜索,我在 Github 上找到了一个已解决的问题,解决了这个问题( Github 问题:与 OAuth2 的深度链接不起作用)。 Basically, we could not use JSON object on authentication request's body.
基本上,我们不能在身份验证请求的正文中使用 JSON object。 We must use
URLSearchParams
object instead.我们必须改用
URLSearchParams
object。
The payload should look like:有效载荷应如下所示:
const payload = new URLSearchParams()
payload.append('client_id', process.env.DISCORD_CLIENT_ID)
payload.append('client_secret', process.env.DISCORD_CLIENT_SECRET)
payload.append('grant_type', 'authorization_code')
payload.append('redirect_uri', process.env.DISCORD_REDIRECT_URI)
payload.append('code', accessCode)
payload.append('scope', 'identify')
payload should not be a js object but a form data ie有效负载不应是 js object 而是表单数据,即
let payload = new FormData();
payload.append("key in string","value in string")
In my case, it was a very silly error.就我而言,这是一个非常愚蠢的错误。 Instead of "response_type", I sent "response_type " (with a space);
我发送的不是“response_type”,而是“response_type”(带空格); I randomly realized when I printed the HTML-formatted string and saw a %20 Make sure the parameters have the correct names!
当我打印 HTML 格式的字符串并看到一个 %20 时,我随机意识到,请确保参数具有正确的名称!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.