Add Auth.requires_response_body attribute (#803)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add Auth.requires_response_body attribute If set then responses are read by the client before being sent back into the auth flow * Update tests and docs * PR fixes * Change example methods
authored by George Kettleborough · committed by GitHub · parent cfe2278 · Browse files · 4 files·+77 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+77 added−0 removed
- tests:+37 added−0 removed
- other:+40 added−0 removed
Provenance
- Commit
b3db9ff- Tree
e89f6ac- Author
George Kettleborough <kettleg@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
cfe2278
4 files changed+77 added−0 removed
modified:docs/advanced.md+35 added
419 unmodified lines420 # `request.headers`, and `request.content`.421 ...422 ```423 424+Similarly, if you are implementing a scheme that requires access to the response body, then use the `requires_response_body` property. You will then be able to access response body properties and methods such as `response.content`, `response.text`, `response.json()`, etc.425+426+```python427+class MyCustomAuth(httpx.Auth):428+ requires_response_body = True429+430+ def __init__(self, access_token, refresh_token, refresh_url):431+ self.access_token = access_token432+ self.refresh_token = refresh_token433+ self.refresh_url = refresh_url434+435+ def auth_flow(self, request):436+ request.headers["X-Authentication"] = self.access_token437+ response = yield request438+439+ if response.status_code == 401:440+ # If the server issues a 401 response, then issue a request to441+ # refresh tokens, and resend the request.442+ refresh_response = yield self.build_refresh_request()443+ self.update_tokens(refresh_response)444+445+ request.headers["X-Authentication"] = self.access_token446+ yield request447+448+ def build_refresh_request(self):449+ # Return an `httpx.Request` for refreshing tokens.450+ ...451+452+ def update_tokens(self, response):453+ # Update the `.access_token` and `.refresh_token` tokens454+ # based on a refresh response.455+ data = response.json()456+ ...457+```458+459 ## SSL certificates460 461 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).462 46 unmodified linesmodified:httpx/_auth.py+1 added
21 unmodified lines22 Base class for all authentication schemes.23 """24 25 requires_request_body = False26+ requires_response_body = False27 28 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:29 """30 Execute the authentication flow.226 unmodified linesmodified:httpx/_client.py+4 added
655 unmodified lines656 auth_flow = auth.auth_flow(request)657 request = next(auth_flow)658 while True:659 response = self.send_single_request(request, timeout)660+ if auth.requires_response_body:661+ response.read()662 try:663 next_request = auth_flow.send(response)664 except StopIteration:665 return response517 unmodified lines1183 auth_flow = auth.auth_flow(request)1184 request = next(auth_flow)1185 while True:1186 response = await self.send_single_request(request, timeout)1187+ if auth.requires_response_body:1188+ await response.aread()1189 try:1190 next_request = auth_flow.send(response)1191 except StopIteration:1192 return response284 unmodified linesmodified:tests/client/test_auth.py+37 added
465 unmodified lines466 yield b"Example request body"467 468 with pytest.raises(RequestBodyUnavailable):469 await client.post(url, data=streaming_body(), auth=auth)470+471+472+@pytest.mark.asyncio473+async def test_auth_reads_response_body() -> None:474+ """475+ Test that we can read the response body in an auth flow if `requires_response_body`476+ is set.477+ """478+479+ class ResponseBodyAuth(Auth):480+ """481+ A mock authentication scheme that requires clients to send an 'Authorization'482+ header, then send back the contents of the response in the 'Authorization'483+ header.484+ """485+486+ requires_response_body = True487+488+ def __init__(self, token):489+ self.token = token490+491+ def auth_flow(492+ self, request: Request493+ ) -> typing.Generator[Request, Response, None]:494+ request.headers["Authorization"] = self.token495+ response = yield request496+ data = response.text497+ request.headers["Authorization"] = data498+ yield request499+500+ url = "https://example.org/"501+ auth = ResponseBodyAuth("xyz")502+ client = AsyncClient(dispatch=MockDispatch())503+504+ response = await client.get(url, auth=auth)505+ assert response.status_code == 200506+ assert response.json() == {"auth": '{"auth": "xyz"}'}