我实施了 Discord Oauth2,以便我的用户可以通过 Discord 进行身份验证来登录我的网站。几个月来,一切正常,现在突然停止工作。
根据 Discord 的 oauth2 说明https://discordapp.com/developers/docs/topics/oauth2#shared-resources,我能够成功获取用于交易访问令牌的访问代码。但是,当我尝试接收访问令牌时,我收到了“invalid_client”错误。
首先,我正在击中这个端点:
https://discordapp.com/api/oauth2/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Flogin%2Fdiscord%2Fcallback&response_type=code&scope=identify%20email%20gdm.join
Run Code Online (Sandbox Code Playgroud)
成功返回以下内容:
http://localhost:5000/login/discord/callback?code={some_access_code}
Run Code Online (Sandbox Code Playgroud)
然后将访问代码发送回 discord 以获取访问令牌。这是失败的代码:
export function getDiscordAccessToken(accessCode, call) {
const redirect = call === 'login' ? process.env.DISCORD_LOGIN_REDIRECT : process.env.DISCORD_CONNECT_REDIRECT
return new Promise((resolve, reject) => {
axios
.post(
`https://discordapp.com/api/oauth2/token?client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=authorization_code&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join`
)
.then(res => {
resolve(res.data)
})
.catch(err => {
// log error to db
console.log("Here is your error: ", err.response)
reject(err.response)
})
})
}
Run Code Online (Sandbox Code Playgroud)
这段代码运行了几个月没有任何问题。然后,突然之间它停止了工作。我什至检查了可以在此处找到的 Discord 更改日志https://discordapp.com/developers/docs/change-log,但我没有发现对身份验证更改的引用。
非常感谢您能提供的任何帮助!
小智 6
查询参数应该在 POST 请求的 BODY 中,而不是oauth/tokenurl 的 URL。
Discord 最近推送了对 oAuth2 的更新,使其更受标准的限制。这意味着它们不再支持 POST 的 URL 中的参数,而是要求它们在正文中并进行表单编码(基本相同,但在正文中并且没有前导?)。
所以你基本上需要(未测试):
axios
.post(
"https://discordapp.com/api/oauth2/token",
"client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=client_credentials&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join"
)
Run Code Online (Sandbox Code Playgroud)
我知道问题已经得到解答,但就我而言,我复制了错误的密钥。只要确保您复制了正确的即可。
密钥位于 OAuth2 选项卡下,而不是在 Discord 开发人员仪表板上的“常规信息”选项卡下。
| 归档时间: |
|
| 查看次数: |
3335 次 |
| 最近记录: |