0
# Authentication
1
2
Authentication handlers for various HTTP authentication schemes. The requests library provides built-in support for the most common authentication methods and allows for custom authentication handlers.
3
4
## Capabilities
5
6
### Base Authentication Class
7
8
All authentication handlers inherit from the AuthBase class.
9
10
```python { .api }
11
class AuthBase:
12
"""Base class that all authentication implementations derive from."""
13
14
def __call__(self, request):
15
"""
16
Apply authentication to a request.
17
18
Parameters:
19
- request: PreparedRequest object to modify
20
21
Returns:
22
Modified PreparedRequest object
23
"""
24
```
25
26
### HTTP Basic Authentication
27
28
Implements HTTP Basic Authentication using username and password.
29
30
```python { .api }
31
class HTTPBasicAuth(AuthBase):
32
"""Attaches HTTP Basic Authentication to the given Request object."""
33
34
def __init__(self, username: str, password: str):
35
"""
36
Initialize Basic Authentication.
37
38
Parameters:
39
- username: Username for authentication
40
- password: Password for authentication
41
"""
42
43
def __call__(self, request) -> 'PreparedRequest':
44
"""Apply Basic Authentication to request."""
45
46
def __eq__(self, other) -> bool:
47
"""Check equality with another auth object."""
48
49
def __ne__(self, other) -> bool:
50
"""Check inequality with another auth object."""
51
```
52
53
### HTTP Digest Authentication
54
55
Implements HTTP Digest Authentication for enhanced security over Basic auth.
56
57
```python { .api }
58
class HTTPDigestAuth(AuthBase):
59
"""Attaches HTTP Digest Authentication to the given Request object."""
60
61
def __init__(self, username: str, password: str):
62
"""
63
Initialize Digest Authentication.
64
65
Parameters:
66
- username: Username for authentication
67
- password: Password for authentication
68
"""
69
70
def __call__(self, request) -> 'PreparedRequest':
71
"""Apply Digest Authentication to request."""
72
```
73
74
### HTTP Proxy Authentication
75
76
Implements HTTP Proxy Authentication, extending Basic Authentication for proxy servers.
77
78
```python { .api }
79
class HTTPProxyAuth(HTTPBasicAuth):
80
"""Attaches HTTP Proxy Authentication to a given Request object."""
81
82
def __call__(self, request) -> 'PreparedRequest':
83
"""Apply Proxy Authentication to request."""
84
```
85
86
## Usage Examples
87
88
### Basic Authentication
89
90
```python
91
import requests
92
from requests.auth import HTTPBasicAuth
93
94
# Using auth tuple (shorthand)
95
response = requests.get('https://api.example.com/data', auth=('username', 'password'))
96
97
# Using HTTPBasicAuth class
98
basic_auth = HTTPBasicAuth('username', 'password')
99
response = requests.get('https://api.example.com/data', auth=basic_auth)
100
101
# With sessions for persistent auth
102
session = requests.Session()
103
session.auth = ('username', 'password')
104
response = session.get('https://api.example.com/data')
105
```
106
107
### Digest Authentication
108
109
```python
110
import requests
111
from requests.auth import HTTPDigestAuth
112
113
# Digest authentication for enhanced security
114
digest_auth = HTTPDigestAuth('username', 'password')
115
response = requests.get('https://api.example.com/secure', auth=digest_auth)
116
117
# With sessions
118
session = requests.Session()
119
session.auth = HTTPDigestAuth('user', 'pass')
120
response = session.get('https://api.example.com/data')
121
```
122
123
### Proxy Authentication
124
125
```python
126
import requests
127
from requests.auth import HTTPProxyAuth
128
129
# Authenticate with proxy server
130
proxy_auth = HTTPProxyAuth('proxy_user', 'proxy_pass')
131
proxies = {'http': 'http://proxy.example.com:8080'}
132
133
response = requests.get('https://api.example.com/data',
134
auth=proxy_auth,
135
proxies=proxies)
136
```
137
138
### Custom Authentication
139
140
```python
141
import requests
142
from requests.auth import AuthBase
143
144
class TokenAuth(AuthBase):
145
"""Custom token-based authentication."""
146
147
def __init__(self, token):
148
self.token = token
149
150
def __call__(self, request):
151
request.headers['Authorization'] = f'Bearer {self.token}'
152
return request
153
154
# Use custom authentication
155
token_auth = TokenAuth('your-api-token')
156
response = requests.get('https://api.example.com/data', auth=token_auth)
157
```
158
159
### OAuth 1.0 Authentication
160
161
```python
162
# Note: OAuth requires additional libraries like requests-oauthlib
163
from requests_oauthlib import OAuth1
164
165
# OAuth 1.0 authentication
166
oauth = OAuth1('client_key', 'client_secret', 'resource_owner_key', 'resource_owner_secret')
167
response = requests.get('https://api.twitter.com/1.1/account/verify_credentials.json', auth=oauth)
168
```
169
170
### Bearer Token Authentication
171
172
```python
173
import requests
174
175
# Simple bearer token authentication
176
headers = {'Authorization': 'Bearer your-access-token'}
177
response = requests.get('https://api.example.com/data', headers=headers)
178
179
# Or create a custom auth class
180
class BearerAuth(requests.auth.AuthBase):
181
def __init__(self, token):
182
self.token = token
183
184
def __call__(self, r):
185
r.headers["Authorization"] = f"Bearer {self.token}"
186
return r
187
188
# Use the custom auth
189
bearer_auth = BearerAuth('your-access-token')
190
response = requests.get('https://api.example.com/data', auth=bearer_auth)
191
```
192
193
### Multiple Authentication Methods
194
195
```python
196
import requests
197
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
198
199
# Try different auth methods
200
def authenticate_with_fallback(url, username, password):
201
# Try Digest first (more secure)
202
try:
203
response = requests.get(url, auth=HTTPDigestAuth(username, password))
204
if response.status_code == 200:
205
return response
206
except requests.exceptions.RequestException:
207
pass
208
209
# Fall back to Basic auth
210
try:
211
response = requests.get(url, auth=HTTPBasicAuth(username, password))
212
return response
213
except requests.exceptions.RequestException:
214
pass
215
216
# Try without auth
217
return requests.get(url)
218
219
response = authenticate_with_fallback('https://api.example.com/data', 'user', 'pass')
220
```
221
222
### Session-based Authentication
223
224
```python
225
import requests
226
227
# Login to get session cookie
228
session = requests.Session()
229
login_data = {'username': 'user', 'password': 'pass'}
230
session.post('https://example.com/login', data=login_data)
231
232
# Subsequent requests use the session cookie
233
response = session.get('https://example.com/protected-data')
234
235
# Or combine with other auth methods
236
session.auth = ('api_user', 'api_pass')
237
response = session.get('https://api.example.com/data')
238
```
239
240
## Authentication with Different Request Types
241
242
### GET with Authentication
243
244
```python
245
import requests
246
247
# Simple GET with auth
248
response = requests.get('https://api.example.com/users', auth=('user', 'pass'))
249
users = response.json()
250
```
251
252
### POST with Authentication
253
254
```python
255
import requests
256
257
# POST data with authentication
258
data = {'name': 'John Doe', 'email': 'john@example.com'}
259
response = requests.post('https://api.example.com/users',
260
json=data,
261
auth=('admin', 'password'))
262
```
263
264
### File Upload with Authentication
265
266
```python
267
import requests
268
269
# Upload file with authentication
270
files = {'file': open('document.pdf', 'rb')}
271
response = requests.post('https://api.example.com/upload',
272
files=files,
273
auth=('user', 'pass'))
274
```
275
276
## Security Considerations
277
278
### HTTPS Requirement
279
280
Always use HTTPS when sending authentication credentials:
281
282
```python
283
import requests
284
285
# Good - HTTPS protects credentials
286
response = requests.get('https://api.example.com/data', auth=('user', 'pass'))
287
288
# Bad - HTTP exposes credentials
289
# response = requests.get('http://api.example.com/data', auth=('user', 'pass'))
290
```
291
292
### Environment Variables
293
294
Store credentials in environment variables instead of hardcoding:
295
296
```python
297
import os
298
import requests
299
300
username = os.environ.get('API_USERNAME')
301
password = os.environ.get('API_PASSWORD')
302
303
if username and password:
304
response = requests.get('https://api.example.com/data', auth=(username, password))
305
else:
306
raise ValueError("Missing authentication credentials")
307
```
308
309
### Certificate Verification
310
311
Always verify SSL certificates in production:
312
313
```python
314
import requests
315
316
# Default behavior - verify SSL certificates
317
response = requests.get('https://api.example.com/data',
318
auth=('user', 'pass'),
319
verify=True) # This is the default
320
321
# Only disable verification for testing
322
# response = requests.get('https://api.example.com/data',
323
# auth=('user', 'pass'),
324
# verify=False) # Only for testing!
325
```
326
327
## Authentication Utility Function
328
329
```python { .api }
330
def _basic_auth_str(username: str, password: str) -> str:
331
"""
332
Generate a Basic Auth string.
333
334
Parameters:
335
- username: Username for authentication
336
- password: Password for authentication
337
338
Returns:
339
Basic authentication header value
340
"""
341
```
342
343
This utility function is used internally by HTTPBasicAuth but can be useful for custom authentication implementations.