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

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

问题描述

我正在尝试通过使用服务帐户使用域范围委派进行 google drive API 调用.我可以使身份验证正常工作,但不能使驱动器 api 调用.错误:在驱动器中创建文件时找不到文件

此外,在域范围委派之前,我通过与服务帐户共享驱动器文件夹使其工作.但现在我希望它在不共享的情况下工作.

我想我需要在某个地方做一些 setServiceAccount 的事情.不确定会发生在哪里.

const {google} = require('googleapis');const auth = 新的 google.auth.JWT(客户电子邮件,空,私有密钥,['https://www.googleapis.com/auth/drive']);const drive = google.drive({version: "v3", auth});//drive.files.create({});

解决方案

答案:

您需要将从 GCP 控制台获取的 Service Account 私钥传递给您的 JWT 客户端,并指定您希望模拟为 subject 的用户.p>

代码:

获取私钥后,您需要将其传递给您的 JWT 客户端,然后再进行授权:

让 google = require('googleapis');让 privateKey = require("./privatekey.json");var jwtClient = 新的 google.auth.JWT({电子邮件:privateKey.client_email,密钥:privateKey.private_key,范围:['https://www.googleapis.com/auth/drive'],主题:'user@domain.com'});jwtClient.authorize(函数(错误,令牌){如果(错误){控制台日志(错误);返回;}别的 {console.log("连接成功!");}});

然后,您可以使用 Drive 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.

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

解决方案

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

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

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

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