0

やりたいこと

discordのOAuth2を使用してユーザーの情報を取得してみたい

発生している問題

コードを実行したら{ message: '401: Unauthorized', code: 0 }これがconsoleに表示される

コード

const fetch = require('node-fetch');
const express = require('express');
const router = express.Router();

router.get('/', async ({ query }, response) => {
    const { code } = query;

    if (code) {
        try {
            const oauthResult = await fetch('https://discord.com/api/oauth2/token', {
                method: 'POST',
                body: new URLSearchParams({
                    client_id: '',
                    client_secret: '',
                    code,
                    grant_type: 'authorization_code',
                    redirect_uri: `https://oauth.aiueominato1111.repl.co`,
                    scope: 'identify',
                }),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            });

            const oauthData = await oauthResult.json();

            const userResult = await fetch('https://discord.com/api/users/@me', {
                headers: {
                    authorization: `${oauthData.token_type} ${oauthData.access_token}`,
                },
            });

            console.log(await userResult.json());
        } catch (error) {
            // NOTE: An unauthorized token will not throw an error;
            // it will return a 401 Unauthorized response in the try block above
            console.log(error);
        }
    }

    return response.render('login', { root: '.' });
});
module.exports = router;

1 件の回答 1

0

tokenエンドポイントへのリクエストで 401 が返るということはクライアント認証に失敗しているのだと思います。

client_id, client_secret に設定している値を見直してみてください。
(他のパラメータが誤っている場合には(Discordサービスの実装にも依りますが、典型的には) 400 が返ると思われます)

参考:

1
  • client secretを確認したら間違っていました! 回答ありがとうございました!
    – user48118
    2021年11月5日 12:16

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。