Debian Codegraph @

docs/advanced/authentication.md

raw
1 Authentication can either be included on a per-request basis...
2
3 ```pycon
4 >>> auth = httpx.BasicAuth(username="username", password="secret")
5 >>> client = httpx.Client()
6 >>> response = client.get("https://www.example.com/", auth=auth)
7 ```
8
9 Or configured on the client instance, ensuring that all outgoing requests will include authentication credentials...
10
11 ```pycon
12 >>> auth = httpx.BasicAuth(username="username", password="secret")
13 >>> client = httpx.Client(auth=auth)
14 >>> response = client.get("https://www.example.com/")
15 ```
16
17 ## Basic authentication
18
19 HTTP 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.
20
21 ```pycon
22 >>> auth = httpx.BasicAuth(username="finley", password="secret")
23 >>> client = httpx.Client(auth=auth)
24 >>> response = client.get("https://httpbin.org/basic-auth/finley/secret")
25 >>> response
26 <Response [200 OK]>
27 ```
28
29 ## Digest authentication
30
31 HTTP 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.
32
33 ```pycon
34 >>> 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 >>> response
38 <Response [200 OK]>
39 >>> response.history
40 [<Response [401 UNAUTHORIZED]>]
41 ```
42
43 ## NetRC authentication
44
45 HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.
46
47 The `.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.
48
49 Example `.netrc` file:
50
51 ```
52 machine example.org
53 login example-username
54 password example-password
55
56 machine python-httpx.org
57 login other-username
58 password other-password
59 ```
60
61 Some examples of configuring `.netrc` authentication with `httpx`.
62
63 Use the default `.netrc` file in the users home directory:
64
65 ```pycon
66 >>> auth = httpx.NetRCAuth()
67 >>> client = httpx.Client(auth=auth)
68 ```
69
70 Use an explicit path to a `.netrc` file:
71
72 ```pycon
73 >>> auth = httpx.NetRCAuth(file="/path/to/.netrc")
74 >>> client = httpx.Client(auth=auth)
75 ```
76
77 Use the `NETRC` environment variable to configure a path to the `.netrc` file,
78 or fallback to the default.
79
80 ```pycon
81 >>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))
82 >>> client = httpx.Client(auth=auth)
83 ```
84
85 The `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.
86
87 ## Custom authentication schemes
88
89 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...
90
91 * 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`.
95
96 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...
97
98 ```python
99 class MyCustomAuth(httpx.Auth):
100 def __init__(self, token):
101 self.token = token
102
103 def auth_flow(self, request):
104 # Send the request, with a custom `X-Authentication` header.
105 request.headers['X-Authentication'] = self.token
106 yield request
107 ```
108
109 If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...
110
111 ```python
112 class MyCustomAuth(httpx.Auth):
113 def __init__(self, token):
114 self.token = token
115
116 def auth_flow(self, request):
117 response = yield request
118 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.token
122 yield request
123 ```
124
125 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.
126
127 You will then be able to access `request.content` inside the `.auth_flow()` method.
128
129 ```python
130 class MyCustomAuth(httpx.Auth):
131 requires_request_body = True
132
133 def __init__(self, token):
134 self.token = token
135
136 def auth_flow(self, request):
137 response = yield request
138 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 request
143
144 def sign_request(self, request):
145 # Create a request signature, based on `request.method`, `request.url`,
146 # `request.headers`, and `request.content`.
147 ...
148 ```
149
150 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.
151
152 ```python
153 class MyCustomAuth(httpx.Auth):
154 requires_response_body = True
155
156 def __init__(self, access_token, refresh_token, refresh_url):
157 self.access_token = access_token
158 self.refresh_token = refresh_token
159 self.refresh_url = refresh_url
160
161 def auth_flow(self, request):
162 request.headers["X-Authentication"] = self.access_token
163 response = yield request
164
165 if response.status_code == 401:
166 # If the server issues a 401 response, then issue a request to
167 # refresh tokens, and resend the request.
168 refresh_response = yield self.build_refresh_request()
169 self.update_tokens(refresh_response)
170
171 request.headers["X-Authentication"] = self.access_token
172 yield request
173
174 def build_refresh_request(self):
175 # Return an `httpx.Request` for refreshing tokens.
176 ...
177
178 def update_tokens(self, response):
179 # Update the `.access_token` and `.refresh_token` tokens
180 # based on a refresh response.
181 data = response.json()
182 ...
183 ```
184
185 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`.
186
187 ```python
188 import asyncio
189 import threading
190 import httpx
191
192
193 class MyCustomAuth(httpx.Auth):
194 def __init__(self):
195 self._sync_lock = threading.RLock()
196 self._async_lock = asyncio.Lock()
197
198 def sync_get_token(self):
199 with self._sync_lock:
200 ...
201
202 def sync_auth_flow(self, request):
203 token = self.sync_get_token()
204 request.headers["Authorization"] = f"Token {token}"
205 yield request
206
207 async def async_get_token(self):
208 async with self._async_lock:
209 ...
210
211 async def async_auth_flow(self, request):
212 token = await self.async_get_token()
213 request.headers["Authorization"] = f"Token {token}"
214 yield request
215 ```
216
217 If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.
218
219 ```python
220 import httpx
221 import sync_only_library
222
223
224 class 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 request
229
230 async def async_auth_flow(self, request):
231 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")
232 ```