使用Google身份验证库对Google云端硬盘进行身份验证

时间:2020-05-30 03:09:33

标签: node.js google-api google-authentication google-auth-library

我正在使用节点Google身份验证库来获取授权的客户端。我知道这行从打印正确结果的console.log('Project ID', await auth.getProjectId())行成功。尝试使用此授权客户端来验证Google云端硬盘api时出现错误:

Error: invalid_scope: Invalid OAuth scope or ID token audience provided.

代码:

import { google } from 'googleapis'
const { GoogleAuth } = require('google-auth-library')
import { config } from 'dotenv'
import { resolve } from 'path'

/**
 * GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS are set
 * in the top-level .env file, GoogleAuth requires these to be set
 */
config({ path: resolve(__dirname, '../.env')})

const main = async () => {
    const csv = ''
    const auth = await getAuthClient()
    await uploadToGoogleDrive({ csv, auth })
}

const getAuthClient = async () => {
    const scopes = ['https://www.googleapis.com/auth.drive']
    const auth = new GoogleAuth({ scopes })
    console.log('Project ID', await auth.getProjectId())
    return await auth.getClient()
}

const uploadToGoogleDrive = async ({ csv, auth }) => {
    const drive = google.drive({
        version: 'v3',
        auth,
    })

    await drive.files.create({
        requestBody: {
            name: 'test.csv',
            mimeType: 'text/plain',
            parents: ['** Parent Folder Name **']
        },
        media: {
            mimeType: 'text/csv',
            body: csv
        }
    })
}

main().catch(console.error)

0 个答案:

没有答案