使用域范围内的委派和服务帐户的Google OAuth [英] Google OAuth using domain wide delegation and service account

查看:98
本文介绍了使用域范围内的委派和服务帐户的Google OAuth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过服务帐户使用域范围内的委托进行Google Drive API调用. 我可以使身份验证正常工作,但无法获得驱动器api调用. 错误:在驱动器中创建文件时找不到文件

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.

我认为我需要在某个地方进行一些setServiceAccount的操作.不知道会在哪里发生.

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

推荐答案

答案:

您需要将从GCP控制台获得的服务帐户私钥传递给JWT客户端,并指定要模拟为subject的用户.

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.

获得私钥后,您需要在授权之前将其传递给JWT客户端:

After getting your private key, you need to pass this into your JWT Client before 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!");
  }
});

然后,您可以使用Drive API作为服务帐户来完成操作.

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

希望对您有帮助!

这篇关于使用域范围内的委派和服务帐户的Google OAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆