我试图通过Discord API OAuth2身份验证流程(常规应用程序而非机器人)获取用户电子邮件 .

我可以成功完成OAuth2流程并让用户允许权限让我的应用程序查看他们的电子邮件 . 我将使用电子邮件mmaines@cisco.com(第二个测试用户)下的测试帐户 .

但是,即使我以完全不同的用户身份登录,并按照OAuth2流程获取访问令牌,api / v6 / users / @ me endpoints 也始终返回我的2个测试用户的原始用户对象(即使它应该由于访问令牌是针对第二个测试用户,因此甚至无法访问该帐户 .

下面我将向您介绍我正在使用的整个过程

OAuth2 Authorization URL Using 2nd Test Account

OAuth2 Authorization URL Using 2nd Test Account Screenshot

在链接的屏幕截图中,请注意此处请求的电子邮件是mmaines@cisco.com

server.js (Callback for Authorization Code)

这是我对OAuth2授权的回调

server.get('/auth/discord/callback', function(req, res) {

    const discordUID = req.query.state;

    // Get the access token with email and identify scopes on the mmaines-cisco user
    axios.post(`https://discordapp.com/api/oauth2/token?grant_type=client_credentials&client_id=344539394373582849&client_secret=Cck2cchaqQiLCRASTXhcDwHZscNFLW7u&code=${req.query.code}&scope=email+identify&state=${req.query.state}`, {})
    .then(function(response) {
        console.log(response.data);

        res.cookie("access_token", response.data.access_token);
        res.redirect("/discord/tag-email/");

    }).catch(function(err) {
        console.log(err);
        res.status(500).send(err);
    });

});

Access_Token Recieved

{ 
    access_token: 'loUOWKzOgUj45PSkbGoXUFgY6wQS52',
    token_type: 'Bearer',
    state: '347013221682511873',
    expires_in: 604800,
    scope: 'email identify' 
}

以上是来自/ api / oauth2 / token endpoints 的响应,请注意access_token并注意状态密钥,该状态密钥携带验证访问其电子邮件的用户的Discord用户ID

Redirect Page

此页面是用户在接受授权并允许访问其电子邮件和用户信息后结束的位置 . 在这里,我在客户端上运行api请求,以确保/ users / @ me资源是他们的帐户

请注意,access_token作为cookie传递给客户端(我也尝试将其作为url参数传递,并且具有相同的结果)

index.hbs

<h1>Thank You!</h1>
<h3>Your membership is being unlocked now!</h3>

{{access_token}}

<script>
    console.log(`Bearer {{access_token}}`);
    axios.get(`https://discordapp.com/api/v6/users/@me`, {
        headers: {
            "Authorization": `Bearer {{access_token}}`,
            "Content-Type": "application/x-www-form-urlencoded" 
        }
    })
    .then(function(response) {
        console.log("USER: ", response.data);
    })
    .catch(function(err) {
        console.log(err);
    });
</script>

ScreenShot of Index Route After User Authorization and Received User Object From Discord API

ScreenShot of the recieved user object from the Discord API

请注意, usernameuser-idemail 都与预期值不同(这些是我的主要测试帐户中的值) . 我从所有discord客户端的主要测试帐户注销,并作为我的第二个测试用户登录到Web客户端 .

另请注意,打印出来的access_token与我们在获得第二个测试帐户授权后从api收到的相同

The Question

我不知道为什么api / v6 / users / @ me endpoints 返回一个用户对象

  • access_token甚至不能访问主要测试帐户信息

  • 未从api调用时登录的用户返回用户信息

有关为什么会这样的想法?感谢您阅读本文,并提前感谢您的帮助 .