authentication.md
This file
Path
docs/advanced/authentication.md
232 lines · 8.4 KiB · Markdown
Last changed by
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
History of this fileTake it
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 1–232why, one step back1Authentication can either be included on a per-request basis...23```pycon4>>> auth = httpx.BasicAuthentication(username="username", password="secret")5>>> client = httpx.Client()6>>> response = client.get("https://www.example.com/", auth=auth)7```89Or configured on the client instance, ensuring that all outgoing requests will include authentication credentials...1011```pycon12>>> auth = httpx.BasicAuthentication(username="username", password="secret")13>>> client = httpx.Client(auth=auth)14>>> response = client.get("https://www.example.com/")15```1617## Basic authentication1819HTTP basic authentication is an unencrypted authentication scheme that uses a simple encoding of the username and password in the request `Authorization` header. Since it is unencrypted it should typically only be used over `https`, although this is not strictly enforced.2021```pycon22>>> auth = httpx.BasicAuthentication(username="finley", password="secret")23>>> client = httpx.Client(auth=auth)24>>> response = client.get("https://httpbin.org/basic-auth/finley/secret")25>>> response26<Response [200 OK]>27```2829## Digest authentication3031HTTP digest authentication is a challenge-response authentication scheme. Unlike basic authentication it provides encryption, and can be used over unencrypted `http` connections. It requires an additional round-trip in order to negotiate the authentication. 3233```pycon34>>> auth = httpx.DigestAuth(username="olivia", password="secret")35>>> client = httpx.Client(auth=auth)36>>> response = client.get("https://httpbin.org/digest-auth/auth/olivia/secret")37>>> response38<Response [200 OK]>39>>> response.history40[<Response [401 UNAUTHORIZED]>]41```4243## NetRC authentication4445HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.4647The `.netrc` config file allows authentication credentials to be associated with specified hosts. When a request is made to a host that is found in the netrc file, the username and password will be included using HTTP basic authentication.4849Example `.netrc` file:5051```52machine example.org53login example-username54password example-password5556machine python-httpx.org57login other-username58password other-password59```6061Some examples of configuring `.netrc` authentication with `httpx`.6263Use the default `.netrc` file in the users home directory:6465```pycon66>>> auth = httpx.NetRCAuth()67>>> client = httpx.Client(auth=auth)68```6970Use an explicit path to a `.netrc` file:7172```pycon73>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")74>>> client = httpx.Client(auth=auth)75```7677Use the `NETRC` environment variable to configure a path to the `.netrc` file,78or fallback to the default.7980```pycon81>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))82>>> client = httpx.Client(auth=auth)83```8485The `NetRCAuth()` class uses [the `netrc.netrc()` function from the Python standard library](https://docs.python.org/3/library/netrc.html). See the documentation there for more details on exceptions that may be raised if the `.netrc` file is not found, or cannot be parsed.8687## Custom authentication schemes8889When 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...9091* A two-tuple of `username`/`password`, to be used with basic authentication.92* An instance of `httpx.BasicAuth()`, `httpx.DigestAuth()`, or `httpx.NetRCAuth()`.93* A callable, accepting a request and returning an authenticated request instance.94* An instance of subclasses of `httpx.Auth`.9596The 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...9798```python99class MyCustomAuth(httpx.Auth):100 def __init__(self, token):101 self.token = token102103 def auth_flow(self, request):104 # Send the request, with a custom `X-Authentication` header.105 request.headers['X-Authentication'] = self.token106 yield request107```108109If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...110111```python112class MyCustomAuth(httpx.Auth):113 def __init__(self, token):114 self.token = token115116 def auth_flow(self, request):117 response = yield request118 if response.status_code == 401:119 # If the server issues a 401 response then resend the request,120 # with a custom `X-Authentication` header.121 request.headers['X-Authentication'] = self.token122 yield request123```124125Custom 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.126127You will then be able to access `request.content` inside the `.auth_flow()` method.128129```python130class MyCustomAuth(httpx.Auth):131 requires_request_body = True132133 def __init__(self, token):134 self.token = token135136 def auth_flow(self, request):137 response = yield request138 if response.status_code == 401:139 # If the server issues a 401 response then resend the request,140 # with a custom `X-Authentication` header.141 request.headers['X-Authentication'] = self.sign_request(...)142 yield request143144 def sign_request(self, request):145 # Create a request signature, based on `request.method`, `request.url`,146 # `request.headers`, and `request.content`.147 ...148```149150Similarly, 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.151152```python153class MyCustomAuth(httpx.Auth):154 requires_response_body = True155156 def __init__(self, access_token, refresh_token, refresh_url):157 self.access_token = access_token158 self.refresh_token = refresh_token159 self.refresh_url = refresh_url160161 def auth_flow(self, request):162 request.headers["X-Authentication"] = self.access_token163 response = yield request164165 if response.status_code == 401:166 # If the server issues a 401 response, then issue a request to167 # refresh tokens, and resend the request.168 refresh_response = yield self.build_refresh_request()169 self.update_tokens(refresh_response)170171 request.headers["X-Authentication"] = self.access_token172 yield request173174 def build_refresh_request(self):175 # Return an `httpx.Request` for refreshing tokens.176 ...177178 def update_tokens(self, response):179 # Update the `.access_token` and `.refresh_token` tokens180 # based on a refresh response.181 data = response.json()182 ...183```184185If 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`.186187```python188import asyncio189import threading190import httpx191192193class MyCustomAuth(httpx.Auth):194 def __init__(self):195 self._sync_lock = threading.RLock()196 self._async_lock = asyncio.Lock()197198 def sync_get_token(self):199 with self._sync_lock:200 ...201202 def sync_auth_flow(self, request):203 token = self.sync_get_token()204 request.headers["Authorization"] = f"Token {token}"205 yield request206207 async def async_get_token(self):208 async with self._async_lock:209 ...210211 async def async_auth_flow(self, request):212 token = await self.async_get_token()213 request.headers["Authorization"] = f"Token {token}"214 yield request215```216217If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.218219```python220import httpx221import sync_only_library222223224class MyCustomAuth(httpx.Auth):225 def sync_auth_flow(self, request):226 token = sync_only_library.get_token(...)227 request.headers["Authorization"] = f"Token {token}"228 yield request229230 async def async_auth_flow(self, request):231 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")232```