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
Provenance
- Commit
12dd157- Tree
f8f4098- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
c5037f0
8 files changed+131 added−14 removed
modified:docs/advanced.md+63 added
378 unmodified lines379 ...380 }381 ```382 383+## Customizing authentication384+385+When 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...386+387+* 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`.391+392+The 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...393+394+```python395+class MyCustomAuth(httpx.Auth):396+ def __init__(self, token):397+ self.token = token398+399+ def auth_flow(self, request):400+ # Send the request, with a custom `X-Authentication` header.401+ request.headers['X-Authentication'] = self.token402+ yield request403+```404+405+If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...406+407+```python408+class MyCustomAuth(httpx.Auth):409+ def __init__(self, token):410+ self.token = token411+412+ 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+```420+421+Custom 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.422+423+You will then be able to access `request.content` inside the `.auth_flow()` method.424+425+```python426+class MyCustomAuth(httpx.Auth):427+ requires_request_body = True428+429+ def __init__(self, token):430+ self.token = token431+432+ 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 request439+440+ def sign_request(self, request):441+ # Create a request signature, based on `request.method`, `request.url`,442+ # `request.headers`, and `request.content`.443+ ...444+```445+446 ## SSL certificates447 448 When 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 linesmodified:httpx/__init__.py+4 added-1 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request, stream3-from .auth import BasicAuth, DigestAuth3+from .auth import Auth, BasicAuth, DigestAuth4 from .client import AsyncClient, Client5 from .config import TimeoutConfig # For 0.8 backwards compat.6 from .config import PoolLimits, Proxy, Timeout7 from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode10 unmodified lines18 ProxyError,19 ReadTimeout,20 RedirectLoop,21 RequestBodyUnavailable,22+ RequestNotRead,23 ResponseClosed,24 ResponseNotRead,25 StreamConsumed,26 TimeoutException,18 unmodified lines45 "request",46 "stream",47 "codes",48 "AsyncClient",49+ "Auth",50 "BasicAuth",51 "Client",52 "DigestAuth",53 "PoolLimits",15 unmodified lines69 "RedirectLoop",70 "RequestBodyUnavailable",71 "ResponseClosed",72 "ResponseNotRead",73+ "RequestNotRead",74 "StreamConsumed",75 "ProxyError",76 "TooManyRedirects",77 "WriteTimeout",10 unmodified linesmodified:httpx/auth.py+6 added-6 removed
8 unmodified lines9 from .exceptions import ProtocolError, RequestBodyUnavailable10 from .models import Request, Response11 from .utils import to_bytes, to_str, unquote12 13-AuthFlow = typing.Generator[Request, Response, None]14-13 AuthTypes = typing.Union[14 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],15 typing.Callable[["Request"], "Request"],16 "Auth",4 unmodified lines21 """22 Base class for all authentication schemes.23 """24 27- def __call__(self, request: Request) -> AuthFlow:25+ requires_request_body = False26+27+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:28 """29 Execute the authentication flow.30 31 To dispatch a request, `yield` it:25 unmodified lines57 58 def __init__(self, func: typing.Callable[[Request], Request]) -> None:59 self.func = func60 61- def __call__(self, request: Request) -> AuthFlow:61+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:62 yield self.func(request)63 64 65 class BasicAuth(Auth):6 unmodified lines72 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]73 ):74 self.auth_header = self.build_auth_header(username, password)75 76- 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 request79 80 def build_auth_header(21 unmodified lines102 ) -> None:103 self.username = to_bytes(username)104 self.password = to_bytes(password)105 106- 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 linesmodified:httpx/client.py+4 added-1 removed
674 unmodified lines675 history: typing.List[Response],676 auth: Auth,677 timeout: Timeout,678 ) -> Response:679+ if auth.requires_request_body:680+ await request.aread()681+679- 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 linesmodified:httpx/exceptions.py+6 added
144 unmodified lines145 after a streaming response.146 """147 148 149+class RequestNotRead(StreamError):150+ """151+ Attempted to access request content, without having called `read()`.152+ """153+154+155 class ResponseClosed(StreamError):156 """157 Attempted to read or stream response content, but the request has been158 closed.16 unmodified linesmodified:httpx/models.py+19 added
31 unmodified lines32 CookieConflict,33 HTTPError,34 InvalidURL,35 NotRedirectResponse,36+ RequestNotRead,37 ResponseClosed,38 ResponseNotRead,39 StreamConsumed,40 )600 unmodified lines641 642 for item in reversed(auto_headers):643 self.headers.raw.insert(0, item)644 645+ @property646+ def content(self) -> bytes:647+ if not hasattr(self, "_content"):648+ raise RequestNotRead()649+ return self._content650+651+ 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._content662+663 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 linesmodified:tests/client/test_auth.py+6 added-2 removed
6 unmodified lines7 8 from httpx import (9 URL,10 AsyncClient,11+ Auth,12 DigestAuth,13 ProtocolError,14 Request,15 RequestBodyUnavailable,16 Response,17 )17-from httpx.auth import Auth, AuthFlow18 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes19 from httpx.dispatch.base import AsyncDispatcher20 21 395 unmodified lines417 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers418 of intermediate responses.419 """420 421+ requires_request_body = True422+423 def __init__(self, repeat: int):424 self.repeat = repeat425 424- def __call__(self, request: Request) -> AuthFlow:426+ def auth_flow(427+ self, request: Request428+ ) -> typing.Generator[Request, Response, None]:429 nonces = []430 431 for index in range(self.repeat):432 request.headers["Authorization"] = f"Repeat {index}"37 unmodified linesmodified:tests/models/test_requests.py+23 added-4 removed
19 unmodified lines20 21 @pytest.mark.asyncio22 async 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()25 26 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"27- assert content == b"test=123"27+ assert request.content == b"test=123"28 29 30 @pytest.mark.asyncio31 async 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()34 35 assert request.headers["Content-Type"] == "application/json"36- assert content == b'{"test": 123}'36+ assert request.content == b'{"test": 123}'37 38 39+@pytest.mark.asyncio40+async 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.content47+48+49+@pytest.mark.asyncio50+async 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.content56+57+58 def test_transfer_encoding_header():59 async def streaming_body(data):60 yield data # pragma: nocover61 52 unmodified lines