0
# Authentication
1
2
Comprehensive authentication support including SASL mechanisms, token-based authentication, and Claims-Based Security (CBS) for Azure services and other AMQP brokers.
3
4
## Capabilities
5
6
### Base Authentication
7
8
Base authentication class that provides common functionality for all authentication mechanisms.
9
10
```python { .api }
11
class AMQPAuth:
12
def __init__(self, hostname, port=None, verify=None, http_proxy=None,
13
transport_type=TransportType.Amqp, encoding='UTF-8'):
14
"""
15
Base AMQP authentication mixin class.
16
17
Parameters:
18
- hostname (str): AMQP broker hostname
19
- port (int): AMQP broker port (default: None, auto-selected based on transport)
20
- verify (str): Path to CA certificate file for TLS verification
21
- http_proxy (dict): HTTP proxy configuration
22
- transport_type (TransportType): Transport protocol (Amqp, AmqpOverWebsocket)
23
- encoding (str): Character encoding
24
"""
25
```
26
27
**Key Methods:**
28
29
```python { .api }
30
def set_io(self, hostname, port, http_proxy, transport_type):
31
"""Set the IO handler for the connection."""
32
33
def set_wsio(self, hostname, port, http_proxy):
34
"""Set WebSocket IO handler."""
35
36
def set_tlsio(self, hostname, port):
37
"""Set TLS IO handler."""
38
39
def close(self):
40
"""Close authentication session."""
41
```
42
43
### SASL Authentication
44
45
#### SASLAnonymous
46
47
Anonymous authentication for brokers that allow unauthenticated access.
48
49
```python { .api }
50
class SASLAnonymous(AMQPAuth):
51
def __init__(self, hostname, port=5671, verify=None, http_proxy=None,
52
transport_type=None, encoding='UTF-8'):
53
"""
54
Anonymous SASL authentication.
55
56
Parameters:
57
- hostname (str): AMQP broker hostname
58
- port (int): AMQP broker port
59
- verify (str): Path to CA certificate file
60
- http_proxy (dict): HTTP proxy configuration
61
- transport_type (TransportType): Transport protocol
62
- encoding (str): Character encoding
63
"""
64
```
65
66
**Usage Example:**
67
68
```python
69
from uamqp.authentication import SASLAnonymous
70
71
# Anonymous authentication (for development/testing)
72
auth = SASLAnonymous("localhost", port=5672) # Non-TLS port for local testing
73
```
74
75
#### SASLPlain
76
77
Username and password authentication using SASL PLAIN mechanism.
78
79
```python { .api }
80
class SASLPlain(AMQPAuth):
81
def __init__(self, hostname, username, password, port=5671, verify=None,
82
http_proxy=None, transport_type=None, encoding='UTF-8'):
83
"""
84
Username/password SASL authentication.
85
86
Parameters:
87
- hostname (str): AMQP broker hostname
88
- username (str): Authentication username
89
- password (str): Authentication password
90
- port (int): AMQP broker port
91
- verify (str): Path to CA certificate file
92
- http_proxy (dict): HTTP proxy configuration
93
- transport_type (TransportType): Transport protocol
94
- encoding (str): Character encoding
95
"""
96
```
97
98
**Usage Example:**
99
100
```python
101
from uamqp.authentication import SASLPlain
102
103
# Username/password authentication
104
auth = SASLPlain(
105
hostname="amqp.example.com",
106
username="myuser",
107
password="mypassword",
108
port=5671 # AMQPS port
109
)
110
111
# With TLS certificate verification
112
auth = SASLPlain(
113
hostname="amqp.example.com",
114
username="myuser",
115
password="mypassword",
116
verify="/path/to/ca-cert.pem"
117
)
118
```
119
120
### Token-Based Authentication
121
122
#### TokenRetryPolicy
123
124
Configuration for token refresh retry behavior.
125
126
```python { .api }
127
class TokenRetryPolicy:
128
def __init__(self, retries=3, backoff=0):
129
"""
130
Token authentication retry policy.
131
132
Parameters:
133
- retries (int): Number of retry attempts (default: 3)
134
- backoff (float): Delay between retries in milliseconds (default: 0)
135
"""
136
```
137
138
#### CBSAuthMixin
139
140
Base class for Claims-Based Security authentication used by Azure services.
141
142
```python { .api }
143
class CBSAuthMixin(AMQPAuth):
144
def __init__(self, hostname, port=5671, verify=None, http_proxy=None,
145
transport_type=None, encoding='UTF-8', token_retry_policy=None):
146
"""
147
Claims-Based Security authentication mixin.
148
149
Parameters:
150
- hostname (str): AMQP broker hostname
151
- port (int): AMQP broker port
152
- verify (str): Path to CA certificate file
153
- http_proxy (dict): HTTP proxy configuration
154
- transport_type (TransportType): Transport protocol
155
- encoding (str): Character encoding
156
- token_retry_policy (TokenRetryPolicy): Token retry configuration
157
"""
158
159
def update_token(self):
160
"""Update the authentication token."""
161
162
def create_authenticator(self, connection, debug=False, **kwargs):
163
"""Create CBS authenticator for connection."""
164
165
def close_authenticator(self):
166
"""Close the CBS authenticator."""
167
168
def handle_token(self):
169
"""
170
Handle token authentication.
171
172
Returns:
173
tuple[bool, bool]: (success, should_retry)
174
"""
175
```
176
177
#### SASTokenAuth
178
179
Shared Access Signature token authentication for Azure services.
180
181
```python { .api }
182
class SASTokenAuth(AMQPAuth, CBSAuthMixin):
183
def __init__(self, audience, uri, token, expires_in=None, expires_at=None,
184
username=None, password=None, port=None, timeout=10,
185
retry_policy=TokenRetryPolicy(), verify=None,
186
token_type=b"servicebus.windows.net:sastoken", http_proxy=None,
187
transport_type=TransportType.Amqp, encoding='UTF-8', **kwargs):
188
"""
189
Shared Access Signature (SAS) token authentication.
190
191
Parameters:
192
- audience (str): Token audience
193
- uri (str): Resource URI
194
- token (str): SAS token string
195
- expires_in (int): Token lifetime in seconds
196
- expires_at (datetime): Token expiration time
197
- username (str): Optional username
198
- password (str): Optional password
199
- port (int): Service port
200
- timeout (int): Authentication timeout in seconds
201
- retry_policy (TokenRetryPolicy): Token retry configuration
202
- verify (str): Path to CA certificate file
203
- token_type (bytes): Token type identifier
204
- http_proxy (dict): HTTP proxy configuration
205
- transport_type (TransportType): Transport protocol
206
- encoding (str): Character encoding
207
"""
208
209
def update_token(self):
210
"""Update the SAS token."""
211
212
@classmethod
213
def from_shared_access_key(cls, uri, key_name, shared_access_key, expiry=None, **kwargs):
214
"""
215
Create SASTokenAuth from shared access key components.
216
217
Parameters:
218
- uri (str): Resource URI
219
- key_name (str): Shared access key name
220
- shared_access_key (str): Shared access key value
221
- expiry (datetime): Token expiration time
222
223
Returns:
224
SASTokenAuth: Configured authentication instance
225
"""
226
```
227
228
**Usage Examples:**
229
230
```python
231
from uamqp.authentication import SASTokenAuth
232
import datetime
233
234
# SAS token for Azure Service Bus
235
sas_token = "SharedAccessSignature sr=https%3A%2F%2Fmynamespace.servicebus.windows.net%2F&sig=..."
236
auth = SASTokenAuth(
237
hostname="mynamespace.servicebus.windows.net",
238
token=sas_token
239
)
240
241
# SAS token with explicit expiration
242
auth = SASTokenAuth(
243
hostname="mynamespace.servicebus.windows.net",
244
token=sas_token,
245
expires_at=datetime.datetime.utcnow() + datetime.timedelta(hours=1)
246
)
247
```
248
249
#### JWTTokenAuth
250
251
JSON Web Token authentication for services that support JWT tokens.
252
253
```python { .api }
254
class JWTTokenAuth(AMQPAuth, CBSAuthMixin):
255
def __init__(self, audience, uri, get_token,
256
expires_in=datetime.timedelta(seconds=3600), expires_at=None,
257
port=None, timeout=10, retry_policy=TokenRetryPolicy(),
258
verify=None, token_type=b"jwt", http_proxy=None,
259
transport_type=TransportType.Amqp, encoding='UTF-8', **kwargs):
260
"""
261
JSON Web Token (JWT) authentication.
262
263
Parameters:
264
- audience (str): Token audience claim
265
- uri (str): Resource URI
266
- get_token (callable): Function/coroutine to get JWT token
267
- expires_in (timedelta): Token lifetime duration
268
- expires_at (datetime): Token expiration time
269
- port (int): Service port
270
- timeout (int): Authentication timeout in seconds
271
- retry_policy (TokenRetryPolicy): Token retry configuration
272
- verify (str): Path to CA certificate file
273
- token_type (bytes): Token type identifier
274
- http_proxy (dict): HTTP proxy configuration
275
- transport_type (TransportType): Transport protocol
276
- encoding (str): Character encoding
277
"""
278
279
def create_authenticator(self, connection, debug=False, **kwargs):
280
"""Create authenticator for JWT token authentication."""
281
282
def update_token(self):
283
"""Update the JWT token."""
284
```
285
286
**Usage Example:**
287
288
```python
289
from uamqp.authentication import JWTTokenAuth
290
import datetime
291
292
# JWT token authentication
293
jwt_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
294
auth = JWTTokenAuth(
295
hostname="service.example.com",
296
token=jwt_token,
297
audience="https://service.example.com",
298
expires_at=datetime.datetime.utcnow() + datetime.timedelta(hours=1)
299
)
300
```
301
302
### Async Authentication
303
304
Asynchronous versions of authentication classes for use with async AMQP operations.
305
306
#### CBSAsyncAuthMixin
307
308
```python { .api }
309
class CBSAsyncAuthMixin(CBSAuthMixin):
310
"""Async Claims-Based Security authentication mixin."""
311
312
@property
313
def loop(self):
314
"""Event loop for async operations."""
315
316
async def create_authenticator_async(self, connection, debug=False, loop=None, **kwargs):
317
"""Create async CBS authenticator for connection."""
318
319
async def close_authenticator_async(self):
320
"""Close the async CBS authenticator."""
321
322
async def handle_token_async(self):
323
"""
324
Handle async token authentication.
325
326
Returns:
327
tuple[bool, bool]: (success, should_retry)
328
"""
329
```
330
331
#### SASTokenAsync
332
333
```python { .api }
334
class SASTokenAsync(CBSAsyncAuthMixin):
335
def __init__(self, audience, uri, token, expires_in=None, expires_at=None,
336
username=None, password=None, port=None, timeout=10,
337
retry_policy=TokenRetryPolicy(), verify=None,
338
token_type=b"servicebus.windows.net:sastoken", http_proxy=None,
339
transport_type=TransportType.Amqp, encoding='UTF-8', **kwargs):
340
"""Async SAS token authentication."""
341
342
async def update_token(self):
343
"""Update the SAS token asynchronously."""
344
```
345
346
#### JWTTokenAsync
347
348
```python { .api }
349
class JWTTokenAsync(CBSAsyncAuthMixin):
350
def __init__(self, audience, uri, get_token,
351
expires_in=datetime.timedelta(seconds=3600), expires_at=None,
352
port=None, timeout=10, retry_policy=TokenRetryPolicy(),
353
verify=None, token_type=b"jwt", http_proxy=None,
354
transport_type=TransportType.Amqp, encoding='UTF-8', **kwargs):
355
"""Async JWT token authentication."""
356
357
async def create_authenticator_async(self, connection, debug=False, loop=None, **kwargs):
358
"""Create async authenticator for JWT token authentication."""
359
360
async def update_token(self):
361
"""Update the JWT token asynchronously."""
362
```
363
364
**Usage Example:**
365
366
```python
367
from uamqp.authentication import SASTokenAsync
368
from uamqp.async_ops import SendClientAsync
369
370
async def send_message_async():
371
auth = SASTokenAsync(
372
hostname="mynamespace.servicebus.windows.net",
373
token=sas_token
374
)
375
376
async with SendClientAsync(target, auth=auth) as client:
377
await client.send_all_messages_async()
378
```
379
380
## HTTP Proxy Support
381
382
All authentication classes support HTTP proxy configuration for environments that require proxy access:
383
384
```python
385
proxy_config = {
386
'proxy_hostname': 'proxy.company.com',
387
'proxy_port': 8080,
388
'username': 'proxy_user', # Optional
389
'password': 'proxy_pass' # Optional
390
}
391
392
auth = SASLPlain(
393
hostname="amqp.example.com",
394
username="user",
395
password="pass",
396
http_proxy=proxy_config
397
)
398
```
399
400
## Transport Types
401
402
Authentication supports different transport protocols:
403
404
```python
405
from uamqp.constants import TransportType
406
407
# Standard AMQP over TCP
408
auth = SASLPlain(hostname="host", username="user", password="pass",
409
transport_type=TransportType.Amqp)
410
411
# AMQP over WebSocket (for firewalls that block non-HTTP traffic)
412
auth = SASLPlain(hostname="host", username="user", password="pass",
413
transport_type=TransportType.AmqpOverWebsocket,
414
port=443)
415
```
416
417
## Common Authentication Errors
418
419
Authentication operations may raise these exceptions:
420
421
- **AuthenticationException**: General authentication failure
422
- **TokenExpired**: Token has expired and needs refresh
423
- **TokenAuthFailure**: Token authentication specifically failed
424
- **AMQPConnectionError**: Connection failed during authentication