NodeJS google oauth2突然失败,出现错误的认证代码

ybzsozfc  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(92)

bounty已结束。此问题的答案有资格获得+50声望奖励。赏金宽限期19小时后结束。Martin正在寻找一个答案从一个有信誉的来源

我正在尝试写一个使用youtube v3 API的JavaScript文件。
我创建了一个谷歌云项目,启用youtube API,并完成了凭据创建过程,最后导致我下载了一个json文件,其中包含我的客户端id等。

生成的'client_secret.json'文件看起来像这样:

{
    "web": {
        "client_id": "aaaaaa",
        "project_id": "aaaa",
        "auth_uri": "aaaa",
        "token_uri": "aaaa": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "aaaaa",
        "redirect_uris": [
            "http://localhost:3030/"
        ]
    }
}

我有一个名为'attempt.js'的文件:

const { google } = require('googleapis');
const readline = require('readline');
const fs = require('fs');

// YouTube API credentials
var CLIENT_ID = '';
var CLIENT_SECRET = '';
var REDIRECT_URL = '';
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];

main()
async function main() {

    console.log('set auth vars from json file')
    await getAuthVars()
    async function getAuthVars() {
        return new Promise(async function (resolve, reject) {
            fs.readFile('client_secret.json', function processClientSecrets(err, content) {
                if (err) {
                    console.log('Error loading client secret file: ' + err);
                    return;
                }
                content = JSON.parse(content)
                console.log('content=', content)
                CLIENT_SECRET = content.web.client_secret;
                CLIENT_ID = content.web.client_id;
                REDIRECT_URL = content.web.redirect_uris[0];
                resolve()
            });
        })
    }

    console.log('begin auth flow')
    beginAuthFlow()
    async function beginAuthFlow() {

        // Create an OAuth2 client
        const oAuth2Client = new google.auth.OAuth2(
            CLIENT_ID,
            CLIENT_SECRET,
            REDIRECT_URL
        );

        // Generate the authentication URL
        const authUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES
        });

        // Create an interface for reading user input
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        // Ask the user to visit the authentication URL and provide the authorization code
        console.log('Authorize this app by visiting the following URL:');
        console.log(authUrl);
        rl.question('Enter the authorization code: ', (code) => {
            rl.close();
            // Exchange authorization code for access token
            oAuth2Client.getToken(code, (err, token) => {
                if (err) {
                    console.error('Error retrieving access token:', err);
                    return;
                }

                // Set the access token for future requests
                oAuth2Client.setCredentials(token);

                // Create a YouTube service client
                const youtube = google.youtube({
                    version: 'v3',
                    auth: oAuth2Client
                });

                // Retrieve details about the authenticated user's YouTube account
                youtube.channels.list(
                    {
                        mine: true,
                        part: 'snippet,contentDetails,statistics'
                    },
                    (err, res) => {
                        if (err) {
                            console.error('Error retrieving channel details:', err);
                            return;
                        }

                        // Display the channel information
                        const channel = res.data.items[0];
                        console.log('Channel ID:', channel.id);
                        console.log('Channel Title:', channel.snippet.title);
                        console.log('Subscriber Count:', channel.statistics.subscriberCount);
                        console.log('View Count:', channel.statistics.viewCount);
                        console.log('Video Count:', channel.statistics.videoCount);
                    }
                );
            });
        });
    }
}

当我用node attempt.js运行这个文件时,它正确地创建了URL,我认为这很好,因为这意味着我的auth工作正常:

begin auth flow
Authorize this app by visiting the following URL:
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=aaaaaa&response_type=code&client_id=aaaaaaa&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2F
Enter the authorization code:

我转到URL,登录到youtube帐户,它重定向到这样的URL:

http://localhost:3031/?code=4%2F0aaaaaa

所以我复制'code='字符串之后的所有内容,所以下面的文本在我的复制剪贴板中:4%2F0aaaaaa
我把它粘贴到终端窗口中,然后按回车键,这给了我这个错误:

Error retrieving access token: GaxiosError: invalid_grant

data: {
      error: 'invalid_grant',
      error_description: 'Malformed auth code.'
    },

我做错了什么?

u2nhd7ah

u2nhd7ah1#

我从浏览器URL复制的代码必须在脚本中解码:

oAuth2Client.getToken(decodeURIComponent(code), (err, token) => {

作品

相关问题