Example #1
0
def _get_request_header(
    credentials = None
):
  """Gets a request header.

  Args:
    credentials: The credentials to use for GCP services.

  Returns:
    A header dict for requests.
  """
  # If credentials is not given, use the default credentials
  if credentials is None:
    credentials, _ = google.auth.default()

  # Refresh credentials in case it has been expired.
  auth_req = google.auth.transport.requests.Request()
  credentials.refresh(auth_req)

  headers = {}
  # Set user-agent for logging usages.
  headers['user-agent'] = constants.USER_AGENT_FOR_CAIP_TRACKING
  credentials.apply(headers)

  return headers
    def test_apply_without_quota_project_id(self):
        headers = {}
        request = self.make_mock_request(status=http_client.OK,
                                         data=SUCCESS_RESPONSE)
        credentials = self.make_credentials()

        credentials.refresh(request)
        credentials.apply(headers)

        assert headers == {
            "authorization":
            "Bearer {}".format(SUCCESS_RESPONSE["access_token"])
        }
    def test_apply_with_quota_project_id(self):
        headers = {"other": "header-value"}
        request = self.make_mock_request(status=http_client.OK,
                                         data=SUCCESS_RESPONSE)
        credentials = self.make_credentials(quota_project_id=QUOTA_PROJECT_ID)

        credentials.refresh(request)
        credentials.apply(headers)

        assert headers == {
            "other": "header-value",
            "authorization":
            "Bearer {}".format(SUCCESS_RESPONSE["access_token"]),
            "x-goog-user-project": QUOTA_PROJECT_ID,
        }
Example #4
0
def apply_credentials(credentials, headers):
    # oauth2client and google-auth have the same interface for this.
    if not is_valid(credentials):
        refresh_credentials(credentials)
    return credentials.apply(headers)
Example #5
0
def apply_credentials(credentials, headers):
    # oauth2client and google-auth have the same interface for this.
    return credentials.apply(headers)