0
# Authentication
1
2
Multiple authentication methods including Basic, Digest, WSSE, HMAC Digest, and Google Login authentication. Authentication is handled automatically once credentials are configured, with httplib2 selecting the appropriate method based on server challenges.
3
4
## Capabilities
5
6
### Authentication Base Class
7
8
Base class for all authentication implementations providing the common interface for credential management and request/response processing.
9
10
```python { .api }
11
class Authentication:
12
"""Base authentication class for all auth methods."""
13
14
def __init__(self, credentials, host, request_uri, headers, response, content, http):
15
"""
16
Initialize authentication handler.
17
18
Args:
19
credentials (tuple): Username/password credentials
20
host (str): Target hostname
21
request_uri (str): Full request URI
22
headers (dict): Request headers
23
response: HTTP response object
24
content: Response content
25
http: Http client instance
26
"""
27
28
def request(self, method, request_uri, headers, content):
29
"""
30
Modify request headers to add appropriate authorization.
31
Override in subclasses for specific auth methods.
32
33
Args:
34
method (str): HTTP method
35
request_uri (str): Full request URI
36
headers (dict): Request headers to modify
37
content: Request body content
38
"""
39
40
def response(self, response, content):
41
"""
42
Process authentication response for nonce updates, etc.
43
Override in subclasses if needed.
44
45
Args:
46
response: HTTP response object
47
content: Response content
48
49
Returns:
50
bool: True if request should be retried
51
"""
52
```
53
54
### Basic Authentication
55
56
HTTP Basic authentication using base64-encoded username:password credentials.
57
58
```python { .api }
59
class BasicAuthentication(Authentication):
60
"""HTTP Basic authentication implementation."""
61
62
def request(self, method, request_uri, headers, content):
63
"""Add Basic Authorization header to request."""
64
```
65
66
### Digest Authentication
67
68
HTTP Digest authentication with MD5 hashing and nonce-based challenge-response.
69
70
```python { .api }
71
class DigestAuthentication(Authentication):
72
"""HTTP Digest authentication implementation."""
73
74
def request(self, method, request_uri, headers, content, cnonce=None):
75
"""
76
Add Digest Authorization header to request.
77
78
Args:
79
method (str): HTTP method
80
request_uri (str): Request URI
81
headers (dict): Request headers
82
content: Request body
83
cnonce (str): Client nonce (auto-generated if None)
84
"""
85
86
def response(self, response, content):
87
"""Process digest auth response and update nonce if stale."""
88
```
89
90
### WSSE Authentication
91
92
Web Services Security (WSSE) authentication using username tokens with password digests.
93
94
```python { .api }
95
class WsseAuthentication(Authentication):
96
"""WSSE (Web Services Security) authentication implementation."""
97
98
def request(self, method, request_uri, headers, content):
99
"""Add WSSE Authorization header with username token."""
100
```
101
102
### HMAC Digest Authentication
103
104
HMAC-based digest authentication providing enhanced security over standard digest auth.
105
106
```python { .api }
107
class HmacDigestAuthentication(Authentication):
108
"""HMAC Digest authentication implementation."""
109
110
def request(self, method, request_uri, headers, content):
111
"""Add HMAC Digest Authorization header."""
112
113
def response(self, response, content):
114
"""Process HMAC digest response for integrity/staleness."""
115
```
116
117
### Google Login Authentication
118
119
Google Login authentication for accessing Google APIs and services.
120
121
```python { .api }
122
class GoogleLoginAuthentication(Authentication):
123
"""Google Login authentication implementation."""
124
125
def request(self, method, request_uri, headers, content):
126
"""Add GoogleLogin Authorization header."""
127
```
128
129
### Credential Management
130
131
Classes for managing authentication credentials and client certificates.
132
133
```python { .api }
134
class Credentials:
135
"""Container for username/password credentials."""
136
137
def __init__(self):
138
"""Initialize empty credentials container."""
139
140
def add(self, name, password, domain=""):
141
"""
142
Add credentials for a domain.
143
144
Args:
145
name (str): Username
146
password (str): Password
147
domain (str): Domain/realm (empty for all domains)
148
"""
149
150
def clear(self):
151
"""Remove all stored credentials."""
152
153
def iter(self, domain):
154
"""
155
Iterate over credentials for domain.
156
157
Args:
158
domain (str): Target domain
159
160
Yields:
161
tuple: (username, password) pairs
162
"""
163
164
class KeyCerts(Credentials):
165
"""Container for SSL client certificates."""
166
167
def add(self, key, cert, domain, password):
168
"""
169
Add client certificate for domain.
170
171
Args:
172
key (str): Path to private key file
173
cert (str): Path to certificate file
174
domain (str): Domain for certificate
175
password (str): Private key password
176
"""
177
178
def iter(self, domain):
179
"""
180
Iterate over certificates for domain.
181
182
Args:
183
domain (str): Target domain
184
185
Yields:
186
tuple: (key, cert, password) tuples
187
"""
188
```
189
190
### Usage Examples
191
192
#### Basic Authentication
193
194
```python
195
import httplib2
196
197
h = httplib2.Http()
198
199
# Add credentials for specific domain
200
h.add_credentials('username', 'password', 'api.example.com')
201
202
# Request will automatically use Basic auth if challenged
203
(resp, content) = h.request("https://api.example.com/protected")
204
205
if resp.status == 200:
206
print("Authentication successful")
207
```
208
209
#### Multiple Credentials
210
211
```python
212
import httplib2
213
214
h = httplib2.Http()
215
216
# Add credentials for different domains
217
h.add_credentials('user1', 'pass1', 'api1.example.com')
218
h.add_credentials('user2', 'pass2', 'api2.example.com')
219
220
# Add wildcard credentials (applied to any domain)
221
h.add_credentials('defaultuser', 'defaultpass', '')
222
223
# httplib2 will select appropriate credentials based on hostname
224
(resp1, content1) = h.request("https://api1.example.com/data")
225
(resp2, content2) = h.request("https://api2.example.com/data")
226
```
227
228
#### Client Certificate Authentication
229
230
```python
231
import httplib2
232
233
h = httplib2.Http()
234
235
# Add client certificate for mutual TLS
236
h.add_certificate(
237
key='/path/to/client.key',
238
cert='/path/to/client.crt',
239
domain='secure.example.com',
240
password='keypassword' # If private key is encrypted
241
)
242
243
# Request will use client certificate for SSL/TLS handshake
244
(resp, content) = h.request("https://secure.example.com/api")
245
```
246
247
#### Mixed Authentication
248
249
```python
250
import httplib2
251
252
h = httplib2.Http()
253
254
# Add both credentials and certificates
255
h.add_credentials('apiuser', 'apipass', 'api.example.com')
256
h.add_certificate('/path/to/client.key', '/path/to/client.crt',
257
'secure.example.com')
258
259
# Different authentication methods used based on server requirements
260
(resp1, content1) = h.request("https://api.example.com/data") # HTTP auth
261
(resp2, content2) = h.request("https://secure.example.com/data") # Client cert
262
```
263
264
#### Clearing Credentials
265
266
```python
267
import httplib2
268
269
h = httplib2.Http()
270
h.add_credentials('user', 'pass')
271
272
# Make authenticated requests...
273
(resp, content) = h.request("https://api.example.com/data")
274
275
# Clear all credentials for security
276
h.clear_credentials()
277
278
# Subsequent requests won't include authentication
279
(resp, content) = h.request("https://api.example.com/public")
280
```
281
282
### Authentication Flow
283
284
1. **Initial Request**: Client makes request without authentication
285
2. **Challenge**: Server responds with 401 and WWW-Authenticate header
286
3. **Credential Selection**: httplib2 selects appropriate credentials based on:
287
- Domain matching (exact match or wildcard)
288
- Authentication method supported (Basic, Digest, etc.)
289
4. **Authentication**: Client retries request with appropriate Authorization header
290
5. **Automatic Handling**: Future requests to same domain automatically include auth
291
292
### Supported Authentication Methods
293
294
#### HTTP Basic
295
- Simple username:password encoding
296
- Base64 encoded credentials
297
- Suitable for HTTPS connections
298
- Widely supported
299
300
#### HTTP Digest
301
- Challenge-response mechanism
302
- MD5 hashing with nonces
303
- More secure than Basic auth
304
- Protects against replay attacks
305
306
#### WSSE (Web Services Security)
307
- Username token with password digest
308
- Timestamp-based nonce generation
309
- Used in web services
310
- SOAP/XML-based authentication
311
312
#### HMAC Digest
313
- Enhanced digest authentication
314
- HMAC-based message authentication
315
- Stronger cryptographic security
316
- Less common but more secure
317
318
#### Google Login
319
- Google-specific authentication
320
- OAuth-style token authentication
321
- For Google APIs and services
322
- Requires Google account credentials
323
324
### Security Considerations
325
326
- **HTTPS Required**: Always use HTTPS for Basic authentication
327
- **Credential Storage**: Credentials stored in memory only
328
- **Domain Isolation**: Credentials only sent to matching domains
329
- **Automatic Cleanup**: Use `clear_credentials()` when done
330
- **Certificate Security**: Protect private key files and passwords