为 Google 服务帐户电子邮件创建别名?

Create an alias for a Google Service Account Email?

我与我的 Google 服务帐户电子邮件共享了一个 Google Sheet,它看起来像:

myappname-service@myappname-266229.iam.gserviceaccount.com

这允许我的应用程序访问 Google Sheet。

我希望能够与别名为那个丑陋的自动生成服务的自定义电子邮件地址(例如 google@myappname.com)共享 Google Sheet帐户电子邮件 (myappname-service@myappname-266229.iam.gserviceaccount.com).

我该怎么做?

编辑:

用于与 Google API 交互的代码示例

from google_auth_httplib2 import AuthorizedHttp
from google.oauth2 import service_account
import pygsheets

def _get_gc():
    scope = ['https://www.googleapis.com/auth/spreadsheets']
    credentials = service_account.Credentials.from_service_account_file(
        settings.GOOGLE_SERVICE_AUTH_FILE,
        scopes=scope,
    )
    http = AuthorizedHttp(credentials, http=HTTP)
    logger.info('Created GC creds, returning...')
    return pygsheets.authorize(custom_credentials=credentials, http=http)


def do_something(url):
    gc = _get_gc()
    spreadsheet = gc.open_by_url(url)

问题 – 服务帐户不能有别名:

与普通帐户不同,服务帐户不能有别名。他们的电子邮件地址定义为:

  • 对应项目名称
  • 服务帐户的名称。

你不能给它额外的别名。

解决方法——模拟普通帐户:

如果您想避免与自动生成的服务帐户电子邮件地址共享 Google 表格,但又想继续使用该服务帐户与 API 进行交互,您最好的选择是在与API.

1。委派 domain-wide 权限:

服务帐户最有用的功能之一是您可以授予它模拟您域中的任何用户并代表它访问数据的能力。这称为 domain-wide 授权,可以通过以下 these steps:

为服务帐户激活

重要提示:您需要成为 G Suite 域的管理员才能委派 domain-wide 权限

2。模拟:

此时,您的服务帐户可以模拟帐户中的任何用户。要真正模拟一个帐户,您只需要在构建凭据时指定要模拟的帐户。

在您的特定情况下,您需要在调用 from_service_account_file 时提供参数 subject,如您在 this page 的 domain-wide 委托部分中所见:

    credentials = service_account.Credentials.from_service_account_file(
        settings.GOOGLE_SERVICE_AUTH_FILE,
        scopes=scope,
        subject="your-account@your-domain.com"
    )

参考: