python - 使用 Google Apps 脚本 API 可执行文件的服务器到服务器身份验证

标签 python python-3.x google-apps-script google-api

我正在尝试为我正在设置的 Python 微服务设置一个具有服务器到服务器身份验证的 Google 应用程序脚本 API 可执行文件。

使用快速入门,我能够通过 Auth2 使其工作,但我无法使其与服务帐户一起工作。我将脚本和电子表格的访问权限授予了服务帐户电子邮件。客户端 secret JSON 中的项目 ID 与应用脚本的项目 ID 匹配。我将它部署为一个 API 可执行文件。

下面是我的代码(虽然我不认为代码是问题所在):

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from googleapiclient.discovery import build


scopes = [
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/script.external_request',
    'https://www.googleapis.com/auth/script.storage',
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/userinfo.email'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scopes)
http_auth = credentials.authorize(Http())
service = build('script', 'v1', http=http_auth)


request = {'function': 'testApi'}
response = service.scripts().run(body=request, scriptId='SCRIPT_ID').execute()

print(response)

我的应用脚本中的 testApi 函数是一个返回“有效”的简单函数。

我一直收到用户在使用个人帐户时没有权限 (403),在使用组织(G Suite 帐户)时甚至没有 500。

如前所述,Google 文档中的快速入门教程有效,但这没有使用服务帐户。

有没有人使 Google Apps Scripts API 可执行并与服务器到服务器身份验证帐户流一起工作?

最佳答案

您可能想查看有关 Using Google Service Accounts with Google Apps Script 的教程。此示例代码展示了如何使用 Service Accounts 在 Google Apps 脚本中使用 OAuth。

要使此代码正常工作,您需要将 create a Google Service accountdomain-wide delegation 进行比较,将私钥和客户端电子邮件替换为实际值,并将客户端 ID 添加到具有 Drive API Scope 的 Google Apps 管理控制台。 OAuth 2.0 访问 token 存储在脚本属性中。

var JSON = {
    "private_key": "Your Private Key",
    "client_email": "serviceacount@project-ctrlq.iam.gserviceaccount.com",
    "client_id": "1234567890",
    "user_email": "amit@labnol.org"
};

function getOAuthService(user) {
    return OAuth2.createService("Service Account")
        .setTokenUrl('https://accounts.google.com/o/oauth2/token')
        .setPrivateKey(JSON.private_key)
        .setIssuer(JSON.client_email)
        .setSubject(JSON.user_email)
        .setPropertyStore(PropertiesService.getScriptProperties())
        .setParam('access_type', 'offline')
        .setScope('https://www.googleapis.com/auth/drive');
}

function getUserFiles() {
    var service = getOAuthService();
    service.reset();
    if (service.hasAccess()) {
        var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1';
        var response = UrlFetchApp.fetch(url, {
            headers: {
                Authorization: 'Bearer ' + service.getAccessToken()
            }
        });
        Logger.log(response.getContentText());
    }
}

function reset() {
    var service = getOAuthService();
    service.reset();
}

此外,如果您收到 403 Insufficient permission 错误,可能是因为应用程序请求访问未在 Google Apps 管理控制台中授权的 API 范围。 invalid_grant 错误可能是由于托管应用程序的服务器的日期和时间设置不正确所致。

关于python - 使用 Google Apps 脚本 API 可执行文件的服务器到服务器身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773093/

相关文章:

google-apps-script - 如果单元格更改,则发送电子邮件通知

python - 如何对电子邮件回复发表评论?

python-3.x - 如何从 python 3 中的可迭代生成器中采样?

python-3.x - Google Colab(Python、jupyter notebook)终端输入

javascript - 如何根据使用脚本从上一个问题中选择的日期更新 Google 表单上的多项选择问题

javascript - Google 表格将一个单元格更改为另一个单元格

Python 将日期和时间转换为 pandas 索引

python异步发布请求

python - 为 Python 构建 OpenCV

python - 如何打印类属性/元素的文档字符串?