Python google.auth.transport.requests.AuthorizedSession() Examples

The following are 30 code examples of google.auth.transport.requests.AuthorizedSession(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.auth.transport.requests , or try the search function .
Example #1
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #2
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #3
Source File: impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message).decode("utf-8"),
            "delegates": self._delegates,
        }

        headers = {"Content-Type": "application/json"}

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint, headers=headers, json=body
        )

        return base64.b64decode(response.json()["signedBlob"]) 
Example #4
Source File: query.py    From gsheets-db-api with MIT License 6 votes vote down vote up
def run_query(baseurl, query, credentials=None):
    url = '{baseurl}&tq={query}'.format(
        baseurl=baseurl, query=parse.quote(query, safe='/()'))
    headers = {'X-DataSource-Auth': 'true'}

    if credentials:
        session = AuthorizedSession(credentials)
    else:
        session = Session()

    r = session.get(url, headers=headers)
    if r.encoding is None:
        r.encoding = 'utf-8'

    # raise any error messages
    if r.status_code != 200:
        raise ProgrammingError(r.text)

    if r.text.startswith(LEADING):
        result = json.loads(r.text[len(LEADING):])
    else:
        result = r.json()

    return result 
Example #5
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #6
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #7
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #8
Source File: fhir_resources.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def get_session():
    """Creates an authorized Requests Session."""

    # Pass in the credentials and project ID. If none supplied, get them
    # from the environment.
    credentials = service_account.Credentials.from_service_account_file(
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    )
    scoped_credentials = credentials.with_scopes(
        ["https://www.googleapis.com/auth/cloud-platform"]
    )

    # Create a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    return session
# [END healthcare_get_session]


# [START healthcare_create_resource] 
Example #9
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
Example #10
Source File: requests.py    From alfred-gmail with MIT License 6 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 **kwargs):
        super(AuthorizedSession, self).__init__(**kwargs)
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        auth_request_session = requests.Session()

        # Using an adapter to make HTTP requests robust to network errors.
        # This adapter retrys HTTP requests when network errors occur
        # and the requests seems safely retryable.
        retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
        auth_request_session.mount("https://", retry_adapter)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        # Do not pass `self` as the session here, as it can lead to infinite
        # recursion.
        self._auth_request = Request(auth_request_session) 
Example #11
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):

        iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(self.
                                                         _target_credentials.
                                                         signer_email)

        body = {
            "audience": self._target_audience,
            "delegates": self._target_credentials._delegates,
            "includeEmail": self._include_email
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._target_credentials.
                                           _source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            data=json.dumps(body).encode('utf-8'))

        id_token = response.json()['token']
        self.token = id_token
        self.expiry = datetime.fromtimestamp(jwt.decode(id_token,
                                             verify=False)['exp']) 
Example #12
Source File: requests.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 auth_request=None):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
Example #13
Source File: requests.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 auth_request=None):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
Example #14
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):

        iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(self.
                                                         _target_credentials.
                                                         signer_email)

        body = {
            "audience": self._target_audience,
            "delegates": self._target_credentials._delegates,
            "includeEmail": self._include_email
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._target_credentials.
                                           _source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            data=json.dumps(body).encode('utf-8'))

        id_token = response.json()['token']
        self.token = id_token
        self.expiry = datetime.fromtimestamp(jwt.decode(id_token,
                                             verify=False)['exp']) 
Example #15
Source File: requests.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 auth_request=None):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
Example #16
Source File: impersonated_credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):

        iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(self.
                                                         _target_credentials.
                                                         signer_email)

        body = {
            "audience": self._target_audience,
            "delegates": self._target_credentials._delegates,
            "includeEmail": self._include_email
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._target_credentials.
                                           _source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            data=json.dumps(body).encode('utf-8'))

        id_token = response.json()['token']
        self.token = id_token
        self.expiry = datetime.fromtimestamp(jwt.decode(id_token,
                                             verify=False)['exp']) 
Example #17
Source File: requests.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 auth_request=None):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
Example #18
Source File: load_google_sheet_to_warehouse.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_google_spreadsheet_client(credentials_target):
    with credentials_target.open('r') as credentials_file:
        json_creds = json.load(credentials_file)
        credentials = service_account.Credentials.from_service_account_info(
            json_creds,
            scopes=['https://www.googleapis.com/auth/drive.readonly']
        )

    authed_session = AuthorizedSession(credentials)
    return client.Client(None, authed_session) 
Example #19
Source File: gcp_utils.py    From google.cloud with GNU General Public License v3.0 5 votes vote down vote up
def session(self):
        return AuthorizedSession(
            self._credentials()) 
Example #20
Source File: session_utils.py    From dicomweb-client with MIT License 5 votes vote down vote up
def create_session_from_gcp_credentials(
        google_credentials: Optional[Any] = None
    ) -> requests.Session:
    '''Creates an authorized session for Google Cloud Platform.

    Parameters
    ----------
    google_credentials: Any
        Google cloud credentials.
        (see https://cloud.google.com/docs/authentication/production
        for more information on Google cloud authentication).
        If not set, will be initialized to ``google.auth.default()``

    Returns
    -------
    requests.Session
        Google cloud authorized session

    '''
    try:
        from google.auth.transport import requests as google_requests
        if google_credentials is None:
            import google.auth
            google_credentials, _ = google.auth.default(
                scopes=['https://www.googleapis.com/auth/cloud-platform']
            )
    except ImportError:
        raise ImportError(
            'The dicomweb-client package needs to be installed with the '
            '"gcp" extra requirements to support interaction with the '
            'Google Cloud Healthcare API: pip install dicomweb-client[gcp]'
        )
    logger.debug('initialize, authenticate and authorize HTTP session')
    return google_requests.AuthorizedSession(google_credentials) 
Example #21
Source File: requests.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 **kwargs):
        super(AuthorizedSession, self).__init__(**kwargs)
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        # Request instance used by internal methods (for example,
        # credentials.refresh).
        # Do not pass `self` as the session here, as it can lead to infinite
        # recursion.
        self._auth_request = Request() 
Example #22
Source File: api.py    From fiss with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_session():
    """ Sets global __SESSION and __USER_ID if they haven't been set """
    global __SESSION
    global __USER_ID
    
    if __SESSION is None:
        try:
            __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile',
                                                               'https://www.googleapis.com/auth/userinfo.email'])[0])
            health()
            __USER_ID = id_token.verify_oauth2_token(__SESSION.credentials.id_token,
                                                     Request(session=__SESSION))['email']
        except AttributeError:
            __USER_ID = __SESSION.credentials.service_account_email
        except (DefaultCredentialsError, RefreshError) as gae:
            if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
                raise
            logging.warning("Unable to determine/refresh application credentials")
            try:
                subprocess.check_call(['gcloud', 'auth', 'application-default',
                                       'login', '--no-launch-browser'])
                __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile',
                                                                   'https://www.googleapis.com/auth/userinfo.email'])[0])
            except subprocess.CalledProcessError as cpe:
                if cpe.returncode < 0:
                    logging.exception("%s was terminated by signal %d",
                                      cpe.cmd, -cpe.returncode)
                else:
                    logging.exception("%s returned %d", cpe.cmd,
                                      cpe.returncode)
                raise gae 
Example #23
Source File: rest_api.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def _get_session():
    """Provides an authed requests session object."""
    creds, _ = google.auth.default(scopes=[_FIREBASE_SCOPES])
    # Use application default credentials to make the Firebase calls
    # https://firebase.google.com/docs/reference/rest/database/user-auth
    authed_session = AuthorizedSession(creds)
    return authed_session 
Example #24
Source File: a2ml.py    From a2ml with Apache License 2.0 5 votes vote down vote up
def evaluate(self):
        credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
        authed_session = AuthorizedSession(credentials)
        basename="https://automl.googleapis.com/v1beta1/"
        cmd = basename + self.operation_name
        response=authed_session.get(cmd)
        result=json.loads(response.content)
        self.ctx.log("Operation name: {}".format(result["name"]))

        if (("done" in result.keys()) and result["done"]):
            self.ctx.log("Model training complete.")
            self.model_name = result["response"]["name"]
            self.ctx.log("Model full name: {}".format(self.model_name))
            self.ctx.config.set('model_name', self.model_name)
            self.ctx.config.write()
            response = self.client.list_model_evaluations(self.model_name)
            self.ctx.log("List of model evaluations:")
            for evaluation in response:
                self.ctx.log("Model evaluation name: {}".format(evaluation.name))
                self.ctx.log("Model evaluation id: {}".format(evaluation.name.split("/")[-1]))
                self.ctx.log("Model evaluation example count: {}".format(
                    evaluation.evaluated_example_count))
                self.ctx.log("Model evaluation time: {} seconds".format(evaluation.create_time.seconds))
                self.ctx.log("Full model evaluation: {}".format(inspect.getmembers(evaluation) ))
                self.ctx.log("\n")
        else:
            self.ctx.log("Model still training...") 
Example #25
Source File: googlephotos.py    From elodie with Apache License 2.0 5 votes vote down vote up
def set_session(self):
        # Try to load credentials from an auth file.
        # If it doesn't exist or is not valid then catch the 
        #  exception and reauthenticate.
        try:
            creds = Credentials.from_authorized_user_file(self.auth_file, self.scopes)
        except:
            try:
                flow = InstalledAppFlow.from_client_secrets_file(self.secrets_file, self.scopes)
                creds = flow.run_local_server()
                cred_dict = {
                    'token': creds.token,
                    'refresh_token': creds.refresh_token,
                    'id_token': creds.id_token,
                    'scopes': creds.scopes,
                    'token_uri': creds.token_uri,
                    'client_id': creds.client_id,
                    'client_secret': creds.client_secret
                }

                # Store the returned authentication tokens to the auth_file.
                with open(self.auth_file, 'w') as f:
                    f.write(json.dumps(cred_dict))
            except:
                return

        self.session = AuthorizedSession(creds)
        self.session.headers["Content-type"] = "application/octet-stream"
        self.session.headers["X-Goog-Upload-Protocol"] = "raw" 
Example #26
Source File: requests.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        credentials,
        refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
        max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
        refresh_timeout=None,
        auth_request=None,
    ):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout
        self._is_mtls = False

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
Example #27
Source File: impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):

        iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
            self._target_credentials.signer_email
        )

        body = {
            "audience": self._target_audience,
            "delegates": self._target_credentials._delegates,
            "includeEmail": self._include_email,
        }

        headers = {"Content-Type": "application/json"}

        authed_session = AuthorizedSession(
            self._target_credentials._source_credentials, auth_request=request
        )

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            data=json.dumps(body).encode("utf-8"),
        )

        id_token = response.json()["token"]
        self.token = id_token
        self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"]) 
Example #28
Source File: conftest.py    From google-resumable-media-python with Apache License 2.0 5 votes vote down vote up
def authorized_transport():
    credentials, _ = google.auth.default(scopes=(utils.GCS_RW_SCOPE,))
    yield tr_requests.AuthorizedSession(credentials) 
Example #29
Source File: test_download.py    From google-resumable-media-python with Apache License 2.0 5 votes vote down vote up
def request(self, method, url, data=None, headers=None, **kwargs):
        """Implementation of Requests' request."""
        response = tr_requests.AuthorizedSession.request(
            self, method, url, data=data, headers=headers, **kwargs
        )
        response.headers[download_mod._HASH_HEADER] = u"md5={}".format(self.EMPTY_HASH)
        return response 
Example #30
Source File: firetactoe.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def _get_session():
    """Provides an authed requests session object."""
    creds, _ = google.auth.default(scopes=[_FIREBASE_SCOPES])
    authed_session = AuthorizedSession(creds)
    return authed_session