簡體   English   中英

域內的Google Drive API服務帳戶

[英]Google Drive API Service Account inside domain

我必須使用Node.js服務器從Drive上的文件夾下載/上傳/刪除文件。 該文件夾位於公司的G Suite中,公司中只有少數人可以訪問。

我必須使用服務帳戶來執行此操作,問題是:是否可能? 我怎樣才能做到這一點?

我已經閱讀了https://developers.google.com/drive/v2/web/delegationhttps://developers.google.com/identity/protocols/OAuth2ServiceAccount,但我不知道是否可以授予權限服務帳戶訪問公司域內的文件夾,因為服務帳戶是@ developer.gserviceaccount.com,公司的域名是其他的,所以當我嘗試將該服務帳戶添加到該文件夾​​時,會出現錯誤。

如果你可以指導我,我會非常感激的。

謝謝!

您可以將oAuth令牌與權限范圍一起使用:

const path = require('path');

module.exports = (app) => {
    const factory = {};
    factory.connect = (done) => {
        const fs = require('fs');
        const google = require('googleapis');
        const googleAuth = require('google-auth-library');

        const SCOPES = [
            'https://www.googleapis.com/auth/drive.metadata.readonly'
        ];
        const TOKEN_DIR = path.resolve(app.root, 'server','config');
        const TOKEN_PATH = path.resolve(TOKEN_DIR,'token.json');

        const creds = require(path.resolve(app.root, 'server', 'config', 'google_oauth.json'));
        authorize(creds, (ret) => {
            done(null, ret);
        });

        /**
         * Create an OAuth2 client with the given credentials, and then execute the
         * given callback function.
         *
         * @param {Object} credentials The authorization client credentials.
         * @param {function} callback The callback to call with the authorized client.
         */
        function authorize(credentials, callback) {
            const clientSecret = credentials.installed.client_secret;
            const clientId = credentials.installed.client_id;
            const redirectUrl = credentials.installed.redirect_uris[0];
            const auth = new googleAuth();
            const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

            // Check if we have previously stored a token.
            fs.readFile(TOKEN_PATH, function (err, token) {
                if (err) {
                    console.error('[ERROR] Unable to read token', err)
                    getNewToken(oauth2Client, callback);
                } else {
                    oauth2Client.credentials = JSON.parse(token);
                    callback(oauth2Client);
                }
            });
        }

        /**
         * Get and store new token after prompting for user authorization, and then
         * execute the given callback with the authorized OAuth2 client.
         *
         * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
         * @param {getEventsCallback} callback The callback to call with the authorized
         *     client.
         */
        function getNewToken(oauth2Client, callback) {
            const authUrl = oauth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: SCOPES
            });
            console.log('Authorize this app by visiting this url: ', authUrl);
            const readline = require('readline');
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            rl.question('Enter the code from that page here: ', function (code) {
                rl.close();
                oauth2Client.getToken(code, function (err, token) {
                    if (err) {
                        console.log('Error while trying to retrieve access token', err);
                        return;
                    }
                    oauth2Client.credentials = token;
                    storeToken(token);
                    callback(oauth2Client);
                });
            });
        }

        /**
         * Store token to disk be used in later program executions.
         *
         * @param {Object} token The token to store to disk.
         */
        function storeToken(token) {
            try {
                fs.mkdirSync(TOKEN_DIR);
            } catch (err) {
                if (err.code != 'EEXIST') {
                    throw err;
                }
            }
            fs.writeFile(TOKEN_PATH, JSON.stringify(token));
            console.log('Token stored to ' + TOKEN_PATH);
        }

    };
    return factory
};

然后factory.connect(done)done auth使用googleapis

                const google = require('googleapis');
                const service = google.drive('v3');
                service.files.list({
                    auth,
                    pageSize: 10,
                    fields: 'nextPageToken, files(id, name)'
                }, step);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM