Google OAuth using domain wide delegation and service account

那年仲夏 提交于 2020-07-23 07:11:28

问题


I am trying to make google drive API calls using domain wide delegation by using a service account. I can get the authentication working but not the drive api calls. Error: File not found when creating a file in drive

Also before domain wide delegation I made it to work by sharing a drive folder with the service account. But now I want it to work without sharing.

I think i need to do some setServiceAccount stuff somewhere. Not sure where that would happen.

const {google} = require('googleapis');
const auth = new google.auth.JWT(
    client_email, null,
    privateKey, ['https://www.googleapis.com/auth/drive']
);
const drive = google.drive({version: "v3", auth});
//drive.files.create({});

回答1:


Answer:

You need to pass your Service Account private key obtained from the GCP console to your JWT Client, and specify which user you wish to impersonate as a subject.

Code:

After getting your private key, you need to pass this into your JWT Clientbefore authorisation:

let google = require('googleapis');
let privateKey = require("./privatekey.json");

var jwtClient = new google.auth.JWT({
       email: privateKey.client_email,
       key: privateKey.private_key,
       scopes: ['https://www.googleapis.com/auth/drive'],
       subject: 'user@domain.com'
    });

jwtClient.authorize(function (error, tokens) {
  if (error) {
    console.log(error);
    return;
  } 
  else {
    console.log("Successfully connected!");
  }
});

Then you can do as you wish with the Drive API as the service account.

I hope this is helpful to you!



来源:https://stackoverflow.com/questions/61915432/google-oauth-using-domain-wide-delegation-and-service-account

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!