Skip to content
Myr

Add support for sync-specific or async-specific auth flows (#1217)

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

* Add support for async auth flows * Move body logic to Auth, add sync_auth_flow, add NoAuth * Update tests * Stick to next() / __anext__() * Fix undefined name errors * Add docs * Add unit tests for auth classes

authored by Florimond Manca · committed by GitHub · parent 15187e7 · Browse files · 5 files+238 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: Tom Christie <tom@tomchristie.com>

Diff stats

5 files+238 added−14 removed

  • tests:+126 added−0 removed
  • other:+112 added−14 removed

5 files+238 added−14 removed

modified:docs/advanced.md+49 added
722 unmodified lines
723 data = response.json()724 ...725```726727If you _do_ need to perform I/O other than HTTP requests, such as accessing a disk-based cache, or you need to use concurrency primitives, such as locks, then you should override `.sync_auth_flow()` and `.async_auth_flow()` (instead of `.auth_flow()`). The former will be used by `httpx.Client`, while the latter will be used by `httpx.AsyncClient`.728729```python730import asyncio731import threading732import httpx733734735class MyCustomAuth(httpx.Auth):736 def __init__(self):737 self._sync_lock = threading.RLock()738 self._async_lock = asyncio.Lock()739740 def sync_get_token(self):741 with self._sync_lock:742 ...743744 def sync_auth_flow(self, request):745 token = self.sync_get_token()746 request.headers["Authorization"] = f"Token {token}"747 yield request748749 async def async_get_token(self):750 async with self._async_lock:751 ...752753 async def async_auth_flow(self, request):754 token = await self.async_get_token()755 request.headers["Authorization"] = f"Token {token}"756 yield request757```758759If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.760761```python762import httpx763import sync_only_library764765766class MyCustomAuth(httpx.Auth):767 def sync_auth_flow(self, request):768 token = sync_only_library.get_token(...)769 request.headers["Authorization"] = f"Token {token}"770 yield request771772 async def async_auth_flow(self, request):773 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")774```775776## SSL certificates777778When 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).779
173 unmodified lines
modified:httpx/_auth.py+55 added
15 unmodified lines
16 Base class for all authentication schemes.1718 To implement a custom authentication scheme, subclass `Auth` and override19 the `.auth_flow()` method.2021 If the authentication scheme does I/O such as disk access or network calls, or uses22 synchronization primitives such as locks, you should override `.sync_auth_flow()`23 and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized24 implementations that will be used by `Client` and `AsyncClient` respectively.25 """2627 requires_request_body = False28 requires_response_body = False
21 unmodified lines
50 You can dispatch as many requests as is necessary.51 """52 yield request5354 def sync_auth_flow(55 self, request: Request56 ) -> typing.Generator[Request, Response, None]:57 """58 Execute the authentication flow synchronously.5960 By default, this defers to `.auth_flow()`. You should override this method61 when the authentication scheme does I/O and/or uses concurrency primitives.62 """63 if self.requires_request_body:64 request.read()6566 flow = self.auth_flow(request)67 request = next(flow)6869 while True:70 response = yield request71 if self.requires_response_body:72 response.read()7374 try:75 request = flow.send(response)76 except StopIteration:77 break7879 async def async_auth_flow(80 self, request: Request81 ) -> typing.AsyncGenerator[Request, Response]:82 """83 Execute the authentication flow asynchronously.8485 By default, this defers to `.auth_flow()`. You should override this method86 when the authentication scheme does I/O and/or uses concurrency primitives.87 """88 if self.requires_request_body:89 await request.aread()9091 flow = self.auth_flow(request)92 request = next(flow)9394 while True:95 response = yield request96 if self.requires_response_body:97 await response.aread()9899 try:100 request = flow.send(response)101 except StopIteration:102 break103104105class FunctionAuth(Auth):106 """107 Allows the 'auth' argument to be passed as a simple callable function,108 that takes the request, and returns a new, modified request.
211 unmodified lines
modified:httpx/_client.py+8 added-14 removed
783 unmodified lines
784 history: typing.List[Response],785 auth: Auth,786 timeout: Timeout,787 ) -> Response:788 if auth.requires_request_body:789 request.read()790791 auth_flow = auth.auth_flow(request)788 auth_flow = auth.sync_auth_flow(request)789 request = next(auth_flow)790791 while True:792 response = self._send_single_request(request, timeout)795 if auth.requires_response_body:796 response.read()793794 try:795 next_request = auth_flow.send(response)796 except StopIteration:797 return response
607 unmodified lines
1405 history: typing.List[Response],1406 auth: Auth,1407 timeout: Timeout,1408 ) -> Response:1412 if auth.requires_request_body:1413 await request.aread()1409 auth_flow = auth.async_auth_flow(request)1410 request = await auth_flow.__anext__()14111415 auth_flow = auth.auth_flow(request)1416 request = next(auth_flow)1412 while True:1413 response = await self._send_single_request(request, timeout)1419 if auth.requires_response_body:1420 await response.aread()14141415 try:1422 next_request = auth_flow.send(response)1423 except StopIteration:1416 next_request = await auth_flow.asend(response)1417 except StopAsyncIteration:1418 return response1419 except BaseException as exc:1420 await response.aclose()1421 raise exc from None
355 unmodified lines
modified:tests/client/test_auth.py+63 added
1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import os9import threading10import typing1112import httpcore13import pytest
175 unmodified lines
189 request.headers["Authorization"] = data190 yield request191192193class SyncOrAsyncAuth(Auth):194 """195 A mock authentication scheme that uses a different implementation for the196 sync and async cases.197 """198199 def __init__(self) -> None:200 self._lock = threading.Lock()201 self._async_lock = asyncio.Lock()202203 def sync_auth_flow(204 self, request: Request205 ) -> typing.Generator[Request, Response, None]:206 with self._lock:207 request.headers["Authorization"] = "sync-auth"208 yield request209210 async def async_auth_flow(211 self, request: Request212 ) -> typing.AsyncGenerator[Request, Response]:213 async with self._async_lock:214 request.headers["Authorization"] = "async-auth"215 yield request216217218@pytest.mark.asyncio219async def test_basic_auth() -> None:220 url = "https://example.org/"221 auth = ("tomchristie", "password123")
473 unmodified lines
695 response = client.get(url, auth=auth)696697 assert response.status_code == 200698 assert response.json() == {"auth": '{"auth": "xyz"}'}699700701@pytest.mark.asyncio702async def test_async_auth() -> None:703 """704 Test that we can use an auth implementation specific to the async case, to705 support cases that require performing I/O or using concurrency primitives (such706 as checking a disk-based cache or fetching a token from a remote auth server).707 """708 url = "https://example.org/"709 auth = SyncOrAsyncAuth()710711 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:712 response = await client.get(url, auth=auth)713714 assert response.status_code == 200715 assert response.json() == {"auth": "async-auth"}716717718def test_sync_auth() -> None:719 """720 Test that we can use an auth implementation specific to the sync case.721 """722 url = "https://example.org/"723 auth = SyncOrAsyncAuth()724725 with httpx.Client(transport=SyncMockTransport()) as client:726 response = client.get(url, auth=auth)727728 assert response.status_code == 200729 assert response.json() == {"auth": "sync-auth"}
added:tests/test_auth.py+63 added
1"""2Unit tests for auth classes.34Integration tests also exist in tests/client/test_auth.py5"""6import pytest78import httpx91011def test_basic_auth():12 auth = httpx.BasicAuth(username="user", password="pass")13 request = httpx.Request("GET", "https://www.example.com")1415 # The initial request should include a basic auth header.16 flow = auth.sync_auth_flow(request)17 request = next(flow)18 assert request.headers["Authorization"].startswith("Basic")1920 # No other requests are made.21 response = httpx.Response(content=b"Hello, world!", status_code=200)22 with pytest.raises(StopIteration):23 flow.send(response)242526def test_digest_auth_with_200():27 auth = httpx.DigestAuth(username="user", password="pass")28 request = httpx.Request("GET", "https://www.example.com")2930 # The initial request should not include an auth header.31 flow = auth.sync_auth_flow(request)32 request = next(flow)33 assert "Authorization" not in request.headers3435 # If a 200 response is returned, then no other requests are made.36 response = httpx.Response(content=b"Hello, world!", status_code=200)37 with pytest.raises(StopIteration):38 flow.send(response)394041def test_digest_auth_with_401():42 auth = httpx.DigestAuth(username="user", password="pass")43 request = httpx.Request("GET", "https://www.example.com")4445 # The initial request should not include an auth header.46 flow = auth.sync_auth_flow(request)47 request = next(flow)48 assert "Authorization" not in request.headers4950 # If a 401 response is returned, then a digest auth request is made.51 headers = {52 "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'53 }54 response = httpx.Response(55 content=b"Auth required", status_code=401, headers=headers56 )57 request = flow.send(response)58 assert request.headers["Authorization"].startswith("Digest")5960 # No other requests are made.61 response = httpx.Response(content=b"Hello, world!", status_code=200)62 with pytest.raises(StopIteration):63 flow.send(response)