Skip to content
Myr

Public Auth API (#732)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Public Auth API * Minor docs tweak * Request.aread and Request.content * Support requires_request_body * Update tests/models/test_requests.py Co-Authored-By: Florimond Manca <florimond.manca@gmail.com>

authored by Tom Christie · committed by GitHub · parent c5037f0 · Browse files · 8 files+131 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

8 files+131 added−14 removed

  • tests:+29 added−6 removed
  • other:+102 added−8 removed

8 files+131 added−14 removed

modified:docs/advanced.md+63 added
378 unmodified lines
379 ...380}381```382383## Customizing authentication384385When issuing requests or instantiating a client, the `auth` argument can be used to pass an authentication scheme to use. The `auth` argument may be one of the following...386387* A two-tuple of `username`/`password`, to be used with basic authentication.388* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.389* A callable, accepting a request and returning an authenticated request instance.390* A subclass of `httpx.Auth`.391392The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of `httpx.Auth` should implement `def auth_flow(request)`, and yield any requests that need to be made...393394```python395class MyCustomAuth(httpx.Auth):396 def __init__(self, token):397 self.token = token398399 def auth_flow(self, request):400 # Send the request, with a custom `X-Authentication` header.401 request.headers['X-Authentication'] = self.token402 yield request403```404405If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...406407```python408class MyCustomAuth(httpx.Auth):409 def __init__(self, token):410 self.token = token411412 def auth_flow(self, request):413 response = yield request414 if response.status_code == 401:415 # If the server issues a 401 response then resend the request,416 # with a custom `X-Authentication` header.417 request.headers['X-Authentication'] = self.token418 yield request419```420421Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a `requires_request_body` property.422423You will then be able to access `request.content` inside the `.auth_flow()` method.424425```python426class MyCustomAuth(httpx.Auth):427 requires_request_body = True428429 def __init__(self, token):430 self.token = token431432 def auth_flow(self, request):433 response = yield request434 if response.status_code == 401:435 # If the server issues a 401 response then resend the request,436 # with a custom `X-Authentication` header.437 request.headers['X-Authentication'] = self.sign_request(...)438 yield request439440 def sign_request(self, request):441 # Create a request signature, based on `request.method`, `request.url`,442 # `request.headers`, and `request.content`.443 ...444```445446## SSL certificates447448When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).449
99 unmodified lines
modified:httpx/__init__.py+4 added-1 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import BasicAuth, DigestAuth3from .auth import Auth, BasicAuth, DigestAuth4from .client import AsyncClient, Client5from .config import TimeoutConfig # For 0.8 backwards compat.6from .config import PoolLimits, Proxy, Timeout7from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode
10 unmodified lines
18 ProxyError,19 ReadTimeout,20 RedirectLoop,21 RequestBodyUnavailable,22 RequestNotRead,23 ResponseClosed,24 ResponseNotRead,25 StreamConsumed,26 TimeoutException,
18 unmodified lines
45 "request",46 "stream",47 "codes",48 "AsyncClient",49 "Auth",50 "BasicAuth",51 "Client",52 "DigestAuth",53 "PoolLimits",
15 unmodified lines
69 "RedirectLoop",70 "RequestBodyUnavailable",71 "ResponseClosed",72 "ResponseNotRead",73 "RequestNotRead",74 "StreamConsumed",75 "ProxyError",76 "TooManyRedirects",77 "WriteTimeout",
10 unmodified lines
modified:httpx/auth.py+6 added-6 removed
8 unmodified lines
9from .exceptions import ProtocolError, RequestBodyUnavailable10from .models import Request, Response11from .utils import to_bytes, to_str, unquote1213AuthFlow = typing.Generator[Request, Response, None]1413AuthTypes = typing.Union[14 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],15 typing.Callable[["Request"], "Request"],16 "Auth",
4 unmodified lines
21 """22 Base class for all authentication schemes.23 """2427 def __call__(self, request: Request) -> AuthFlow:25 requires_request_body = False2627 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:28 """29 Execute the authentication flow.3031 To dispatch a request, `yield` it:
25 unmodified lines
5758 def __init__(self, func: typing.Callable[[Request], Request]) -> None:59 self.func = func6061 def __call__(self, request: Request) -> AuthFlow:61 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:62 yield self.func(request)636465class BasicAuth(Auth):
6 unmodified lines
72 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]73 ):74 self.auth_header = self.build_auth_header(username, password)7576 def __call__(self, request: Request) -> AuthFlow:76 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:77 request.headers["Authorization"] = self.auth_header78 yield request7980 def build_auth_header(
21 unmodified lines
102 ) -> None:103 self.username = to_bytes(username)104 self.password = to_bytes(password)105106 def __call__(self, request: Request) -> AuthFlow:106 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:107 if not request.stream.can_replay():108 raise RequestBodyUnavailable("Request body is no longer available.")109 response = yield request110
145 unmodified lines
modified:httpx/client.py+4 added-1 removed
674 unmodified lines
675 history: typing.List[Response],676 auth: Auth,677 timeout: Timeout,678 ) -> Response:679 if auth.requires_request_body:680 await request.aread()681679 auth_flow = auth(request)682 auth_flow = auth.auth_flow(request)683 request = next(auth_flow)684 while True:685 response = await self.send_single_request(request, timeout)686 try:
267 unmodified lines
modified:httpx/exceptions.py+6 added
144 unmodified lines
145 after a streaming response.146 """147148149class RequestNotRead(StreamError):150 """151 Attempted to access request content, without having called `read()`.152 """153154155class ResponseClosed(StreamError):156 """157 Attempted to read or stream response content, but the request has been158 closed.
16 unmodified lines
modified:httpx/models.py+19 added
31 unmodified lines
32 CookieConflict,33 HTTPError,34 InvalidURL,35 NotRedirectResponse,36 RequestNotRead,37 ResponseClosed,38 ResponseNotRead,39 StreamConsumed,40)
600 unmodified lines
641642 for item in reversed(auto_headers):643 self.headers.raw.insert(0, item)644645 @property646 def content(self) -> bytes:647 if not hasattr(self, "_content"):648 raise RequestNotRead()649 return self._content650651 async def aread(self) -> bytes:652 """653 Read and return the request content.654 """655 if not hasattr(self, "_content"):656 self._content = b"".join([part async for part in self.stream])657 # If a streaming request has been read entirely into memory, then658 # we can replace the stream with a raw bytes implementation,659 # to ensure that any non-replayable streams can still be used.660 self.stream = ByteStream(self._content)661 return self._content662663 def __repr__(self) -> str:664 class_name = self.__class__.__name__665 url = str(self.url)666 return f"<{class_name}({self.method!r}, {url!r})>"
526 unmodified lines
modified:tests/client/test_auth.py+6 added-2 removed
6 unmodified lines
78from httpx import (9 URL,10 AsyncClient,11 Auth,12 DigestAuth,13 ProtocolError,14 Request,15 RequestBodyUnavailable,16 Response,17)17from httpx.auth import Auth, AuthFlow18from httpx.config import CertTypes, TimeoutTypes, VerifyTypes19from httpx.dispatch.base import AsyncDispatcher2021
395 unmodified lines
417 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers418 of intermediate responses.419 """420421 requires_request_body = True422423 def __init__(self, repeat: int):424 self.repeat = repeat425424 def __call__(self, request: Request) -> AuthFlow:426 def auth_flow(427 self, request: Request428 ) -> typing.Generator[Request, Response, None]:429 nonces = []430431 for index in range(self.repeat):432 request.headers["Authorization"] = f"Repeat {index}"
37 unmodified lines
modified:tests/models/test_requests.py+23 added-4 removed
19 unmodified lines
2021@pytest.mark.asyncio22async def test_url_encoded_data():23 request = httpx.Request("POST", "http://example.org", data={"test": "123"})24 content = b"".join([part async for part in request.stream])24 await request.aread()2526 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"27 assert content == b"test=123"27 assert request.content == b"test=123"282930@pytest.mark.asyncio31async def test_json_encoded_data():32 request = httpx.Request("POST", "http://example.org", json={"test": 123})33 content = b"".join([part async for part in request.stream])33 await request.aread()3435 assert request.headers["Content-Type"] == "application/json"36 assert content == b'{"test": 123}'36 assert request.content == b'{"test": 123}'373839@pytest.mark.asyncio40async def test_read_and_stream_data():41 # Ensure a request may still be streamed if it has been read.42 # Needed for cases such as authentication classes that read the request body.43 request = httpx.Request("POST", "http://example.org", json={"test": 123})44 await request.aread()45 content = b"".join([part async for part in request.stream])46 assert content == request.content474849@pytest.mark.asyncio50async def test_cannot_access_content_without_read():51 # Ensure a request may still be streamed if it has been read.52 #  Needed for cases such as authentication classes that read the request body.53 request = httpx.Request("POST", "http://example.org", json={"test": 123})54 with pytest.raises(httpx.RequestNotRead):55 request.content565758def test_transfer_encoding_header():59 async def streaming_body(data):60 yield data # pragma: nocover61
52 unmodified lines