async def test_hidden_basic_auth(client): """ """ res = await client.hidden_basic_auth('user', 'password', auth=BasicAuth('user', 'password')) assert res['authenticated'] is True
def _get_http_client(self) -> AsyncClientWithBackoff: auth = None if self._use_infura(): auth = BasicAuth(username=os.getenv("INFURA_PROJECT_ID"), password=os.getenv("INFURA_SECRET")) return AsyncClientWithBackoff( auth=auth, timeout=int(os.getenv("BEACON_NODE_RESPONSE_TIMEOUT")), )
async def _send_http_request(self, url: str, payload: Optional[str], method: str = 'post', **kwargs: Any) -> Response: """ Sends the actual HTTP request. Split into its own method so that it can be mocked during unit tests. """ kwargs.setdefault( 'timeout', self.timeout if self.timeout else get_default_timeout(), ) if self.authentication: kwargs.setdefault('auth', BasicAuth(*self.authentication)) self._log( level=DEBUG, message='Sending {method} to {url}: {payload!r}'.format( method=method, payload=payload, url=url, ), context={ 'request_method': method, 'request_kwargs': kwargs, 'request_payload': payload, 'request_url': url, }, ) response = await self.client.request(method=method, url=url, data=payload, **kwargs) self._log( level=DEBUG, message='Receiving {method} from {url}: {response!r}'.format( method=method, response=response.content, url=url, ), context={ 'request_method': method, 'request_kwargs': kwargs, 'request_payload': payload, 'request_url': url, 'response_headers': response.headers, 'response_content': response.content, }, ) return response
def basic_auth_client(): # Give Docker and HTTPBin some time to spin up host = os.environ["HTTPBIN_HOST"] port = os.environ["HTTPBIN_80_TCP_PORT"] client = HttpBinAsyncClient("http://{host}:{port}".format(host=host, port=port), auth=BasicAuth('user', 'password')) return client
def basic_auth_client(backend): # Give Docker and HTTPBin some time to spin up host = os.environ["HTTPBIN_HOST"] port = os.environ["HTTPBIN_80_TCP_PORT"] if backend == 'requests': auth = HTTPBasicAuth('user', 'password') else: auth = BasicAuth('user', 'password') client = HttpBinClient("http://{host}:{port}".format(host=host, port=port), backend=backend, auth=auth) return client
def __init__(self, email: str, password: str, timeout: int = 60) -> None: """Used to create Dathost basic auth. Parameters ---------- email : str Email of dathost account. password : str Password of dathost account. timeout : int, optional by default 60 """ self._basic_auth = BasicAuth(email, password) self._timeout = timeout
def wrapper(*args, **kwargs): try: if args[0].auth: try: assert type(args[0].auth) is tuple assert len(args[0].auth) == 2 except AssertionError: print( "Basic Auth needs to be in the format of (username, password)" ) raise basic_auth = BasicAuth(args[0].auth[0], args[0].auth[1]) kwargs["headers"].update( {"Authorization": basic_auth.auth_header}) except AttributeError: pass return func(*args, **kwargs)
def __init__(self, key_id: str, key: str, timeout: int = 30, chunk_size: int = 5000024) -> None: """Used to interact with B2 account. Parameters ---------- key_id : str Application Key ID. key : str Application Key timeout : int, optional Max time a request can take, by default 30 chunk_size : int, optional File reading chunk size, must be above 5mb, by default 5000024 Notes ----- In theory timeout could be 3 times longer then you set. If a request takes X amount of seconds and then gets 401d the authorize function will be called again and the request reissued. The authorize could take another X amount of seconds and then the reissued request could take another X amount of seconds. """ self._auth = BasicAuth( key_id, key ) self._timeout = timeout self._limits = Limits( max_connections=None, max_keepalive_connections=None ) self._user_agent = ( "backblaze/{0}+python/{1.major}.{1.minor}.{1.micro}".format( __version__, version_info ) ) self.chunk_size = chunk_size self._routes = Routes() self._running_task = False self.account_id = None
async def introspect_token(self, async_client: AsyncClient, token: str) -> OIDCUserModel: """ Introspect the access token to retrieve the user info. Args: token: the access_token Returns: OIDCUserModel from openid server """ await self.check_openid_config(async_client) assert self.openid_config response = await async_client.post( self.openid_config.introspect_endpoint, params={"token": token}, auth=BasicAuth(self.resource_server_id, self.resource_server_secret), headers={"Content-Type": "application/x-www-form-urlencoded"}, ) try: data = dict(response.json()) except JSONDecodeError: logger.warning("Unable to parse introspect response", detail=response.text) raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED, detail=response.text) logger.debug("Response from openid introspect", response=data) if response.status_code not in range(200, 300): logger.warning( "Introspect cannot find an active token, user unauthorized", detail=response.text) raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED, detail=response.text) return OIDCUserModel(data)
def test_auth_basic(self, postgrest_client): postgrest_client.auth(None, username="******", password="******") session = postgrest_client.session assert session.auth._auth_header == BasicAuth("admin", "s3cr3t")._auth_header
def __init__(self, username: Union[None, str], token: Union[None, str], **kwargs): if username and token: kwargs["auth"] = BasicAuth(username=username, password=token) super().__init__(**kwargs)