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
Provenance
- Commit
016e4ee- Tree
d0fe846- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
15187e7
5 files changed+238 added−14 removed
modified:docs/advanced.md+49 added
722 unmodified lines723 data = response.json()724 ...725 ```726 727+If 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`.728+729+```python730+import asyncio731+import threading732+import httpx733+734+735+class MyCustomAuth(httpx.Auth):736+ def __init__(self):737+ self._sync_lock = threading.RLock()738+ self._async_lock = asyncio.Lock()739+740+ def sync_get_token(self):741+ with self._sync_lock:742+ ...743+744+ def sync_auth_flow(self, request):745+ token = self.sync_get_token()746+ request.headers["Authorization"] = f"Token {token}"747+ yield request748+749+ async def async_get_token(self):750+ async with self._async_lock:751+ ...752+753+ async def async_auth_flow(self, request):754+ token = await self.async_get_token()755+ request.headers["Authorization"] = f"Token {token}"756+ yield request757+```758+759+If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.760+761+```python762+import httpx763+import sync_only_library764+765+766+class 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 request771+772+ async def async_auth_flow(self, request):773+ raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")774+```775+776 ## SSL certificates777 778 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).779 173 unmodified linesmodified:httpx/_auth.py+55 added
15 unmodified lines16 Base class for all authentication schemes.17 18 To implement a custom authentication scheme, subclass `Auth` and override19 the `.auth_flow()` method.20+21+ 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 """26 27 requires_request_body = False28 requires_response_body = False21 unmodified lines50 You can dispatch as many requests as is necessary.51 """52 yield request53 54+ def sync_auth_flow(55+ self, request: Request56+ ) -> typing.Generator[Request, Response, None]:57+ """58+ Execute the authentication flow synchronously.59 60+ 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()65+66+ flow = self.auth_flow(request)67+ request = next(flow)68+69+ while True:70+ response = yield request71+ if self.requires_response_body:72+ response.read()73+74+ try:75+ request = flow.send(response)76+ except StopIteration:77+ break78+79+ async def async_auth_flow(80+ self, request: Request81+ ) -> typing.AsyncGenerator[Request, Response]:82+ """83+ Execute the authentication flow asynchronously.84+85+ 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()90+91+ flow = self.auth_flow(request)92+ request = next(flow)93+94+ while True:95+ response = yield request96+ if self.requires_response_body:97+ await response.aread()98+99+ try:100+ request = flow.send(response)101+ except StopIteration:102+ break103+104+105 class 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 linesmodified:httpx/_client.py+8 added-14 removed
783 unmodified lines784 history: typing.List[Response],785 auth: Auth,786 timeout: Timeout,787 ) -> Response:788- if auth.requires_request_body:789- request.read()790-791- auth_flow = auth.auth_flow(request)788+ auth_flow = auth.sync_auth_flow(request)789 request = next(auth_flow)790+791 while True:792 response = self._send_single_request(request, timeout)795- if auth.requires_response_body:796- response.read()793+794 try:795 next_request = auth_flow.send(response)796 except StopIteration:797 return response607 unmodified lines1405 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__()1411 1415- 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()1414+1415 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 None355 unmodified linesmodified:tests/client/test_auth.py+63 added
1+"""2+Integration tests for authentication.3+4+Unit tests for auth classes also exist in tests/test_auth.py5+"""6+import asyncio7 import hashlib8 import os9+import threading10 import typing11 12 import httpcore13 import pytest175 unmodified lines189 request.headers["Authorization"] = data190 yield request191 192 193+class SyncOrAsyncAuth(Auth):194+ """195+ A mock authentication scheme that uses a different implementation for the196+ sync and async cases.197+ """198+199+ def __init__(self) -> None:200+ self._lock = threading.Lock()201+ self._async_lock = asyncio.Lock()202+203+ 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 request209+210+ 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 request216+217+218 @pytest.mark.asyncio219 async def test_basic_auth() -> None:220 url = "https://example.org/"221 auth = ("tomchristie", "password123")473 unmodified lines695 response = client.get(url, auth=auth)696 697 assert response.status_code == 200698 assert response.json() == {"auth": '{"auth": "xyz"}'}699+700+701+@pytest.mark.asyncio702+async 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()710+711+ async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:712+ response = await client.get(url, auth=auth)713+714+ assert response.status_code == 200715+ assert response.json() == {"auth": "async-auth"}716+717+718+def 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()724+725+ with httpx.Client(transport=SyncMockTransport()) as client:726+ response = client.get(url, auth=auth)727+728+ assert response.status_code == 200729+ assert response.json() == {"auth": "sync-auth"}added:tests/test_auth.py+63 added
1+"""2+Unit tests for auth classes.3+4+Integration tests also exist in tests/client/test_auth.py5+"""6+import pytest7+8+import httpx9+10+11+def test_basic_auth():12+ auth = httpx.BasicAuth(username="user", password="pass")13+ request = httpx.Request("GET", "https://www.example.com")14+15+ # 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")19+20+ # 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)24+25+26+def test_digest_auth_with_200():27+ auth = httpx.DigestAuth(username="user", password="pass")28+ request = httpx.Request("GET", "https://www.example.com")29+30+ # 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.headers34+35+ # 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)39+40+41+def test_digest_auth_with_401():42+ auth = httpx.DigestAuth(username="user", password="pass")43+ request = httpx.Request("GET", "https://www.example.com")44+45+ # 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.headers49+50+ # 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")59+60+ # 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)