如何使用刷新令牌刷新 discord Oauth2 访问令牌?

时间:2021-05-19 05:49:37

标签: javascript oauth-2.0 discord.js

我在我的网站上使用了 discord Oauth2。

这是我的代码:

let params = new URLSearchParams(window.location.search);
let info = document.getElementById('info');

if (params.has('code')) {
    let code = params.get('code');

    fetch('https://discord.com/api/oauth2/token', {
        method  : 'POST',
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded'
        },
        body    : new URLSearchParams({
            client_id     : '################',
            client_secret : '######################',
            grant_type    : 'authorization_code',
            code          : code,
            redirect_uri  : 'http://127.0.0.1:5501/public/'
        })
    })
        .then((res) => res.json())
        .then(function(res) {
            setInterval(() => {
                fetch('https://discord.com/api/oauth2/token/revoke', {
                    method  : 'POST',
                    headers : {
                        'Content-Type' : 'application/x-www-form-urlencoded'
                    },
                    body    : new URLSearchParams({
                        client_id     : '############',
                        client_secret : '##################3',
                        grant_type    : 'refresh_token',
                        refresh_token : res.refresh_token
                    })
                });
            }, 10000);
        })
        .then((res) => res.json())
        .then(function(res) {
            fetch('https://discord.com/api/users/@me', {
                headers : {
                    authorization : `${res.token_type} ${res.access_token}`
                }
            })
                .then((res) => res.json())
                .then(function(res) {
                    const username = res.username;
                    info.textContent = username;
                });
        });
}

每当我刷新页面时,刷新令牌就会消失。

但是这段代码给了我以下错误:

<块引用>

TypeError: 无法读取未定义的属性 'json'

就在我获取用户/@me 之前。

1 个答案:

答案 0 :(得分:0)

问题是在之前的 then 处理程序中

.then((res) => res.json())

您没有返回 fetch 给您的承诺,这是链接承诺时所必需的。这里 undefined 得到解决,因为 fetch 在 setInterval 回调中。

您可以做的是 - 在 then 处理程序中返回一个承诺,并在您想要的超时/间隔后将该承诺解析为 fetch 调用(因为 fetch 返回一个承诺)。

例如在您的 then 处理程序中,您可以执行此操作 -

.then(function(res) {
return new Promise((resolve, reject) => {
  setInterval(() => {
    resolve(fetch('https://discord.com/api/oauth2/token/revoke', {
        method  : 'POST',
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded'
        },
        body : new URLSearchParams({
            client_id     : '############',
            client_secret : '##################3',
            grant_type    : 'refresh_token',
            refresh_token : res.refresh_token
        })
    }))
  }, 10000);
 })
})

但是,请注意承诺只会被解决一次。如此有效,setInterval 只会为您解决一次承诺。