Python:如何使用特定用户而不是get_application_default()创建GoogleCredentials

时间:2017-04-04 22:42:09

标签: python gcloud google-cloud-python gcloud-python

我正在更新脚本以调用受OAuth2保护的Google Cloud端点。之前的版本假定以前由gcloud auth login进行身份验证的单个用户,因此能够使用默认值:

credentials = GoogleCredentials.get_application_default()
http = credentials.authorize(http)

但是现在我必须以用户A和一些用户B进行一些调用。我可以在shell中执行这些步骤来生成访问令牌,但我更愿意直接在程序中执行:

gcloud auth login user_A@email.com
gcloud auth print-access-token user_A@email.com

有没有办法为两个不同的电子邮件生成两个Credentials值,而无需运行任何shell命令?

3 个答案:

答案 0 :(得分:5)

我的情况有些不同,但希望您可以找到与您的用例相同的情况。 我正在使用服务帐户进行身份验证。

要成功进行身份验证,您需要三件事

  1. 服务帐户文件。这是您创建服务帐户后获得的JSON文件

  2. 范围。这指定您需要访问的Google API。就我而言,我需要访问Google Groups API。 因此,我需要的范围是:“ https://www.googleapis.com/auth/admin.directory.group

您可以在这里找到所有范围的列表:https://developers.google.com/identity/protocols/googlescopes

  1. 所需用户的电子邮件地址。这是您的服务帐户要模拟的用户的电子邮件地址(user_A@email.com)。就我而言,我需要G Suite管理员的电子邮件,因为他们只能访问Google网上论坛。

以下是等效的Python代码:

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/admin.directory.group"]
SERVICE_ACCOUNT_FILE = "my-service-account.json"

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE,
        scopes=SCOPES,
        subject="admin@example.com")

admin_service = build("admin", "directory_v1", credentials=credentials)
group = admin_service.groups().list(domain="example.com").execute()
print("groups list: ", group)

现在根据您的问题是否要模拟其他用户。然后您可以使用

new_user_email = "user2@example.com"
user2_credentials = credentials.with_subject(new_user_email)
new_service = build("admin", "directory_v1", credentials=user2_credentials)
# use this new_service to call required APIs

以下是使用python库的服务帐户进行认证的文档的链接:https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html

以下是服务帐户的Oauth流程一般如何发生的链接:https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md

我希望这对您有所帮助。

PS-这是我对Stack Overflow的第一个答案,所以请告诉我如何改进我的答案。

答案 1 :(得分:1)

据我了解,您想向OAuth2.0受保护的资源发出请求,并在python代码中指定一个“调用者”帐户。

这是我个人使用的一个不错的功能(它的功能超出了您的需要,因为它的工作方式因调用位置而异)。您只需为其提供要用于该呼叫的帐户的客户ID

def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Args:
      url: The Identity-Aware Proxy-protected URL to fetch.
      client_id: The client ID used by Identity-Aware Proxy.
      method: The request method to use
              ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                If no timeout is provided, it is set to 90 by default.

    Returns:
      The page body, or raises an exception if the page couldn't be retrieved.
    """
    # Set the default timeout, if missing
    if 'timeout' not in kwargs:
        kwargs['timeout'] = 120

    # Figure out what environment we're running in and get some preliminary
    # information about the service account.
    bootstrap_credentials, _ = google.auth.default(
        scopes=[IAM_SCOPE])
    if isinstance(bootstrap_credentials,
                  google.oauth2.credentials.Credentials):
        raise Exception('make_iap_request is only supported for service '
                        'accounts.')
    elif isinstance(bootstrap_credentials,
                    google.auth.app_engine.Credentials):
        requests_toolbelt.adapters.appengine.monkeypatch()

    # For service account's using the Compute Engine metadata service,
    # service_account_email isn't available until refresh is called.
    bootstrap_credentials.refresh(Request())

    signer_email = bootstrap_credentials.service_account_email
    if isinstance(bootstrap_credentials,
                  google.auth.compute_engine.credentials.Credentials):
        # Since the Compute Engine metadata service doesn't expose the service
        # account key, we use the IAM signBlob API to sign instead.
        # In order for this to work:
        #
        # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
        #    You can specify this specific scope when creating a VM
        #    through the API or gcloud. When using Cloud Console,
        #    you'll need to specify the "full access to all Cloud APIs"
        #    scope. A VM's scopes can only be specified at creation time.
        #
        # 2. The VM's default service account needs the "Service Account Actor"
        #    role. This can be found under the "Project" category in Cloud
        #    Console, or roles/iam.serviceAccountActor in gcloud.
        signer = google.auth.iam.Signer(
            Request(), bootstrap_credentials, signer_email)
    else:
        # A Signer object can sign a JWT using the service account's key.
        signer = bootstrap_credentials.signer

    # Construct OAuth 2.0 service account credentials using the signer
    # and email acquired from the bootstrap credentials.
    service_account_credentials = google.oauth2.service_account.Credentials(
        signer, signer_email, token_uri=OAUTH_TOKEN_URI, additional_claims={
            'target_audience': client_id
        })

    # service_account_credentials gives us a JWT signed by the service
    # account. Next, we use that to obtain an OpenID Connect token,
    # which is a JWT signed by Google.
    google_open_id_connect_token = get_google_open_id_connect_token(
        service_account_credentials)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    resp = requests.request(
        method, url,
        headers={'Authorization': 'Bearer {}'.format(
            google_open_id_connect_token)}, **kwargs)
    #time.sleep(50)
    if resp.status_code == 403:
        raise Exception('Service account {} does not have permission to '
                        'access the IAP-protected application.'.format(
                            signer_email))
    elif resp.status_code != 200:
        raise Exception(
            'Bad response from application: {!r} / {!r} / {!r}'.format(
                resp.status_code, resp.headers, resp.text))
    elif rest.status_code == 500:
        time.sleep(90)
        return 'DONE'
    else:
        return resp.text


def get_google_open_id_connect_token(service_account_credentials):
    """Get an OpenID Connect token issued by Google for the service account.

    This function:

      1. Generates a JWT signed with the service account's private key
         containing a special "target_audience" claim.

      2. Sends it to the OAUTH_TOKEN_URI endpoint. Because the JWT in #1
         has a target_audience claim, that endpoint will respond with
         an OpenID Connect token for the service account -- in other words,
         a JWT signed by *Google*. The aud claim in this JWT will be
         set to the value from the target_audience claim in #1.

    For more information, see
    https://developers.google.com/identity/protocols/OAuth2ServiceAccount .
    The HTTP/REST example on that page describes the JWT structure and
    demonstrates how to call the token endpoint. (The example on that page
    shows how to get an OAuth2 access token; this code is using a
    modified version of it to get an OpenID Connect token.)
    """

    service_account_jwt = (
        service_account_credentials._make_authorization_grant_assertion())
    request = google.auth.transport.requests.Request()
    body = {
        'assertion': service_account_jwt,
        'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
    }
    token_response = google.oauth2._client._token_endpoint_request(
        request, OAUTH_TOKEN_URI, body)
    return token_response['id_token']

您可以通过其他方式here来阅读更多内容。

答案 2 :(得分:0)

您可能想要使用

gcloud auth application-default login
gcloud auth application-default print-access-token

而不是gcloud auth login

但是如果你使用的是gcloud凭据(不是应用程序默认值),那么请注意

gcloud auth login

是一个交互式命令。您选择用户在浏览器中登录而不是在命令行上登录。

您可以预先登录,然后使用您想要的凭据。例如:

gcloud auth login --account user_A@email.com
gcloud auth login --account user_B@email.com

这会为凭据存储添加凭据(请注意,此处--account仅用于验证,确保选择的Webflow帐户与此处请求的帐户相同)。您可以通过运行

查看所有可用的凭据
gcloud auth list

然后您可以按需使用特定帐户

gcloud auth print-access-token --account user_A@email.com
gcloud auth print-access-token --account user_B@email.com

请注意,print-access-token是未记录的命令,您只应将其用于调试。

更高级的功能是使用配置

gcloud config configurations list

您可以通过

创建新的
gcloud config configurations create A
gcloud config set account user_A@email.com
gcloud config set project project_A

gcloud config configurations create B
gcloud config set account user_B@email.com
gcloud config set project project_B

然后你可以做

gcloud auth print-access-token --configuration A
gcloud auth print-access-token --configuration B

增加的优势是,您不仅可以配置帐户,还可以配置项目,计算区等其他属性......