def refresh_session(self, session=None): """Return updated session if token has expired, attempts to refresh using newly acquired token. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param session: The session to configure for authentication :type session: requests.Session :rtype: requests.Session. """ if 'refresh_token' in self.token: with self._setup_session() as oauth_session: try: token = oauth_session.refresh_token(self.token_uri, refresh_token=self.token['refresh_token'], verify=self.verify, proxies=self.proxies, timeout=self.timeout) except (RequestException, OAuth2Error, InvalidGrantError) as err: raise_with_traceback(AuthenticationError, "", err) self.token = token self._default_token_cache(self.token) else: self.set_token() return self.signed_session(session)
def clear_cached_token(self): """Clear any stored tokens. :raises: KeyError if failed to clear token. """ try: keyring.delete_password(self.cred_store, self.store_key) except keyring.errors.PasswordDeleteError: raise_with_traceback(KeyError, "Unable to clear token.")
def clear_cached_token(self): """Clear any stored tokens. :raises: KeyError if failed to clear token. :rtype: None """ try: keyring.delete_password(self.cred_store, self.store_key) except keyring.errors.PasswordDeleteError: raise_with_traceback(KeyError, "Unable to clear token.")
def set_token(self): """Get token using Client ID/Secret credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ super(ServicePrincipalCredentials, self).set_token() try: token = self._context.acquire_token_with_client_credentials( self.resource, self.id, self.secret) self.token = self._convert_token(token) except adal.AdalError as err: raise_with_traceback(AuthenticationError, "", err)
def set_token(self): """Get token using Username/Password credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ super(UserPassCredentials, self).set_token() try: token = self._context.acquire_token_with_username_password( self.resource, self.username, self.password, self.id) self.token = self._convert_token(token) except adal.AdalError as err: raise_with_traceback(AuthenticationError, "", err)
def signed_session(self): """Create token-friendly Requests session, using auto-refresh. Used internally when a request is made. :rtype: requests_oauthlib.OAuth2Session :raises: TokenExpiredError if token can no longer be refreshed. """ kwargs = self._parse_token() try: new_session = oauth.OAuth2Session(self.id, token=self.token, **kwargs) return new_session except TokenExpiredError as err: raise_with_traceback(Expired, "", err)
def load(self, filepath): """Load configuration from existing file. :param str filepath: Path to existing config file. :raises: ValueError if supplied config file is invalid. """ try: self._config.read(filepath) self.long_running_operation_timeout = self._config.getint( "Azure", "long_running_operation_timeout") except (ValueError, EnvironmentError, NoOptionError): msg = "Supplied config file incompatible" raise_with_traceback(ValueError, msg) finally: self._clear_config() return super(AzureConfiguration, self).load(filepath)
def signed_session(self): """Create token-friendly Requests session, using auto-refresh. Used internally when a request is made. :rtype: requests_oauthlib.OAuth2Session :raises: TokenExpiredError if token can no longer be refreshed. """ kwargs = self._parse_token() try: new_session = oauth.OAuth2Session( self.id, token=self.token, **kwargs) return new_session except TokenExpiredError as err: raise_with_traceback(Expired, "", err)
def set_token(self): """Get token using Client ID/Secret credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ super(ServicePrincipalCertificateAuth, self).set_token() try: token = self._context.acquire_token_with_client_certificate( self.resource, self.id, self.certificate, self.thumbprint ) self.token = self._convert_token(token) except adal.AdalError as err: raise_with_traceback(AuthenticationError, "", err)
def set_token(self): """Get token using Client ID/Secret credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ session = self._setup_session() try: token = session.fetch_token(self.token_uri, client_id=self.id, resource=self.resource, client_secret=self.secret, response_type="client_credentials", verify=self.verify) except (RequestException, OAuth2Error, InvalidGrantError) as err: raise_with_traceback(AuthenticationError, "", err) else: self.token = token
def load(self, filepath): """Load configuration from existing file. :param str filepath: Path to existing config file. :raises: ValueError if supplied config file is invalid. :rtype: None """ try: self._config.read(filepath) self.long_running_operation_timeout = self._config.getint( "Azure", "long_running_operation_timeout") except (ValueError, EnvironmentError, NoOptionError): msg = "Supplied config file incompatible" raise_with_traceback(ValueError, msg) finally: self._clear_config() return super(AzureConfiguration, self).load(filepath)
def get_token(self): """Get token using Username/Password credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ session = self._setup_session() optional = {} if self.secret: optional['client_secret'] = self.secret try: token = session.fetch_token(self.token_uri, client_id=self.id, username=self.username, password=self.password, resource=self.resource, **optional) except (RequestException, OAuth2Error, InvalidGrantError) as err: raise_with_traceback(AuthenticationError, "", err) self.token = token
def set_token(self): """Get token using Username/Password credentials. :raises: AuthenticationError if credentials invalid, or call fails. """ session = self._setup_session() optional = {} if self.secret: optional['client_secret'] = self.secret try: token = session.fetch_token(self.token_uri, client_id=self.id, username=self.username, password=self.password, resource=self.resource, **optional) except (RequestException, OAuth2Error, InvalidGrantError) as err: raise_with_traceback(AuthenticationError, "", err) self.token = token
def signed_session(self): """Create token-friendly Requests session, using auto-refresh. Used internally when a request is made. :rtype: requests_oauthlib.OAuth2Session :raises: TokenExpiredError if token can no longer be refreshed. """ countdown = float(self.token['expires_at']) - time.time() self.token['expires_in'] = countdown try: new_session = oauth.OAuth2Session( self.id, token=self.token, auto_refresh_url=self.token_uri, auto_refresh_kwargs={'client_id': self.id, 'resource': self.resource}, token_updater=self._default_token_cache) return new_session except TokenExpiredError as err: raise_with_traceback(Expired, "", err)
def signed_session(self): """Create token-friendly Requests session, using auto-refresh. Used internally when a request is made. :rtype: requests_oauthlib.OAuth2Session :raises: TokenExpiredError if token can no longer be refreshed. """ countdown = float(self.token['expires_at']) - time.time() self.token['expires_in'] = countdown try: new_session = oauth.OAuth2Session( self.id, token=self.token, auto_refresh_url=self.token_uri, auto_refresh_kwargs={ 'client_id': self.id, 'resource': self.resource }, token_updater=self._default_token_cache) return new_session except TokenExpiredError as err: raise_with_traceback(Expired, "", err)
def set_token(self, response_url): """Get token using Authorization Code from redirected URL. :param str response_url: The full redirected URL from successful authentication. :raises: AuthenticationError if credentials invalid, or call fails. """ self._check_state(response_url) session = self._setup_session() if response_url.startswith(_http(self.redirect)): response_url = _https(response_url) elif not response_url.startswith(_https(self.redirect)): response_url = _https(self.redirect, response_url) try: token = session.fetch_token(self.token_uri, authorization_response=response_url, verify=self.verify) except (InvalidGrantError, OAuth2Error, MismatchingStateError, RequestException) as err: raise_with_traceback(AuthenticationError, "", err) else: self.token = token
def refresh_session(self, session=None): """Return updated session if token has expired, attempts to refresh using newly acquired token. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param session: The session to configure for authentication :type session: requests.Session :rtype: requests.Session. """ if 'refresh_token' in self.token: try: token = self._context.acquire_token_with_refresh_token( self.token['refresh_token'], self.id, self.resource, self.secret # This is needed when using Confidential Client ) self.token = self._convert_token(token) except adal.AdalError as err: raise_with_traceback(AuthenticationError, "", err) return self.signed_session(session)
async def async_send(self, request, headers=None, content=None, **config): """Prepare and send request object according to configuration. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param content: Any body data to add to the request. :param config: Any specific config overrides """ loop = asyncio.get_event_loop() if self.config.keep_alive and self._session is None: self._session = requests.Session() try: session = self.creds.signed_session(self._session) except TypeError: # Credentials does not support session injection session = self.creds.signed_session() if self._session is not None: _LOGGER.warning( "Your credentials class does not support session injection. Performance will not be at the maximum." ) kwargs = self._configure_session(session, **config) if headers: request.headers.update(headers) if not kwargs.get("files"): request.add_content(content) if request.data: kwargs["data"] = request.data kwargs["headers"].update(request.headers) response = None try: try: future = loop.run_in_executor( None, functools.partial(session.request, request.method, request.url, **kwargs), ) return await future except ( oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError, ) as err: error = "Token expired or is invalid. Attempting to refresh." _LOGGER.warning(error) try: session = self.creds.refresh_session() kwargs = self._configure_session(session) if request.data: kwargs["data"] = request.data kwargs["headers"].update(request.headers) future = loop.run_in_executor( None, functools.partial(session.request, request.method, request.url, **kwargs), ) return await future except ( oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError, ) as err: msg = "Token expired or is invalid." raise_with_traceback(TokenExpiredError, msg, err) except (requests.RequestException, oauth2.rfc6749.errors.OAuth2Error) as err: msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: self._close_local_session_if_necessary(response, session, kwargs["stream"])
async def async_send(self, request, headers=None, content=None, stream=True, **config): """Prepare and send request object according to configuration. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param content: Any body data to add to the request. :param config: Any specific config overrides """ response = None session = self.creds.signed_session() kwargs = self._configure_session(session, **config) kwargs['stream'] = stream loop = asyncio.get_event_loop() request.add_headers(headers if headers else {}) if not kwargs.get('files'): request.add_content(content) try: try: future = loop.run_in_executor( None, functools.partial(session.request, request.method, request.url, data=request.data, headers=request.headers, **kwargs)) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: error = "Token expired or is invalid. Attempting to refresh." _LOGGER.warning(error) try: session = self.creds.refresh_session() kwargs = self._configure_session(session) future = loop.run_in_executor( None, functools.partial(session.request, request.method, request.url, data=request.data, headers=request.headers, **kwargs)) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: msg = "Token expired or is invalid." raise_with_traceback(TokenExpiredError, msg, err) except (requests.RequestException, oauth2.rfc6749.errors.OAuth2Error) as err: msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: if not response or not stream: session.close()