簡體   English   中英

Google OAuth 使用域范圍的委派和服務帳戶

[英]Google OAuth using domain wide delegation and service account

我正在嘗試通過使用服務帳戶使用域范圍委派使谷歌驅動器 API 調用。 我可以使身份驗證正常工作,但不能使驅動器 api 調用。 錯誤:在驅動器中創建文件時找不到文件

同樣在域范圍委派之前,我通過與服務帳戶共享驅動器文件夾使其工作。 但現在我希望它在不共享的情況下工作。

我想我需要在某個地方做一些 setServiceAccount 的事情。 不知道會發生在哪里。

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({});

回答:

您需要將從 GCP 控制台獲取的 Service Account 私鑰傳遞給您的 JWT 客戶端,並指定您希望模擬為subject的用戶。

代碼:

獲取您的私鑰后,您需要在授權之前將其傳遞給您的 JWT 客戶端:

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!");
  }
});

然后,您可以使用 Drive API 作為服務帳戶隨心所欲地進行操作。

我希望這對你有幫助!

暫無
暫無

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

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