0
# Authentication and Security
1
2
Comprehensive authentication methods, Shared Access Signature (SAS) generation, and access control mechanisms for secure queue operations.
3
4
## Capabilities
5
6
### Authentication Methods
7
8
Multiple authentication approaches for different security requirements and deployment scenarios.
9
10
```python { .api }
11
# Connection String Authentication
12
client = QueueServiceClient.from_connection_string(
13
"DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey"
14
)
15
16
# Account Key Authentication
17
client = QueueServiceClient(
18
account_url="https://myaccount.queue.core.windows.net",
19
credential="account_key_string"
20
)
21
22
# SAS Token Authentication
23
client = QueueServiceClient(
24
account_url="https://myaccount.queue.core.windows.net",
25
credential="sas_token_string"
26
)
27
28
# Azure Active Directory Authentication
29
from azure.identity import DefaultAzureCredential
30
31
credential = DefaultAzureCredential()
32
client = QueueServiceClient(
33
account_url="https://myaccount.queue.core.windows.net",
34
credential=credential
35
)
36
```
37
38
### Account SAS Generation
39
40
Generate account-level Shared Access Signatures for flexible resource access control.
41
42
```python { .api }
43
def generate_account_sas(
44
account_name: str,
45
account_key: str,
46
resource_types: Union[ResourceTypes, str],
47
permission: Union[AccountSasPermissions, str],
48
expiry: Union[datetime, str],
49
start: Optional[Union[datetime, str]] = None,
50
ip: Optional[str] = None,
51
*,
52
services: Union[Services, str] = Services(queue=True),
53
sts_hook: Optional[Callable[[str], None]] = None,
54
**kwargs
55
) -> str:
56
"""
57
Generate account-level SAS token for multiple resources.
58
59
Parameters:
60
- account_name: Storage account name
61
- account_key: Storage account access key
62
- resource_types: Resource types accessible (service, container, object)
63
- permission: Permissions granted by the SAS
64
- expiry: Token expiration time
65
- start: Token start time (default: now)
66
- ip: IP address or range restriction
67
- services: Services accessible (blob, queue, fileshare)
68
- sts_hook: Optional callback for token signing
69
70
Returns:
71
SAS token string for URL or credential use
72
"""
73
```
74
75
### Queue SAS Generation
76
77
Generate queue-specific Shared Access Signatures for granular queue access control.
78
79
```python { .api }
80
def generate_queue_sas(
81
account_name: str,
82
queue_name: str,
83
account_key: str,
84
permission: Optional[Union[QueueSasPermissions, str]] = None,
85
expiry: Optional[Union[datetime, str]] = None,
86
start: Optional[Union[datetime, str]] = None,
87
policy_id: Optional[str] = None,
88
ip: Optional[str] = None,
89
protocol: Optional[str] = None,
90
*,
91
sts_hook: Optional[Callable[[str], None]] = None,
92
**kwargs
93
) -> str:
94
"""
95
Generate queue-specific SAS token.
96
97
Parameters:
98
- account_name: Storage account name
99
- queue_name: Target queue name
100
- account_key: Storage account access key
101
- permission: Queue permissions (read, add, update, process)
102
- expiry: Token expiration time (required if no policy_id)
103
- start: Token start time
104
- policy_id: Stored access policy identifier
105
- ip: IP address or range restriction
106
- protocol: Protocol restriction ('https' or 'https,http')
107
- sts_hook: Optional callback for token signing
108
109
Returns:
110
SAS token string for queue access
111
"""
112
```
113
114
## Usage Examples
115
116
### Basic Authentication Patterns
117
118
```python
119
from azure.storage.queue import QueueServiceClient
120
121
# Method 1: Connection String (simplest for development)
122
service_client = QueueServiceClient.from_connection_string(
123
"DefaultEndpointsProtocol=https;AccountName=mystorageaccount;AccountKey=mykey;EndpointSuffix=core.windows.net"
124
)
125
126
# Method 2: Account URL + Key (explicit credential management)
127
service_client = QueueServiceClient(
128
account_url="https://mystorageaccount.queue.core.windows.net",
129
credential="account_access_key"
130
)
131
132
# Method 3: Azure Active Directory (recommended for production)
133
from azure.identity import DefaultAzureCredential
134
135
credential = DefaultAzureCredential()
136
service_client = QueueServiceClient(
137
account_url="https://mystorageaccount.queue.core.windows.net",
138
credential=credential
139
)
140
```
141
142
### Account SAS Token Generation
143
144
```python
145
from azure.storage.queue import generate_account_sas, ResourceTypes, AccountSasPermissions, Services
146
from datetime import datetime, timedelta
147
148
# Generate account SAS with queue access
149
sas_token = generate_account_sas(
150
account_name="mystorageaccount",
151
account_key="account_access_key",
152
resource_types=ResourceTypes(service=True, container=True, object=True),
153
permission=AccountSasPermissions(
154
read=True,
155
write=True,
156
delete=True,
157
list=True,
158
add=True,
159
process=True
160
),
161
expiry=datetime.utcnow() + timedelta(hours=24),
162
start=datetime.utcnow(),
163
services=Services(queue=True)
164
)
165
166
# Use SAS token to create client
167
service_client = QueueServiceClient(
168
account_url="https://mystorageaccount.queue.core.windows.net",
169
credential=sas_token
170
)
171
```
172
173
### Queue-Specific SAS Generation
174
175
```python
176
from azure.storage.queue import generate_queue_sas, QueueSasPermissions
177
from datetime import datetime, timedelta
178
179
# Generate read-only SAS for specific queue
180
read_sas = generate_queue_sas(
181
account_name="mystorageaccount",
182
queue_name="myqueue",
183
account_key="account_access_key",
184
permission=QueueSasPermissions(read=True, process=True), # Read metadata, get/delete messages
185
expiry=datetime.utcnow() + timedelta(hours=2)
186
)
187
188
# Generate write-only SAS for message production
189
write_sas = generate_queue_sas(
190
account_name="mystorageaccount",
191
queue_name="myqueue",
192
account_key="account_access_key",
193
permission=QueueSasPermissions(add=True, update=True), # Send and update messages
194
expiry=datetime.utcnow() + timedelta(hours=12)
195
)
196
197
# Create clients with specific permissions
198
read_client = QueueClient(
199
account_url="https://mystorageaccount.queue.core.windows.net",
200
queue_name="myqueue",
201
credential=read_sas
202
)
203
204
write_client = QueueClient(
205
account_url="https://mystorageaccount.queue.core.windows.net",
206
queue_name="myqueue",
207
credential=write_sas
208
)
209
```
210
211
### Stored Access Policy Usage
212
213
```python
214
from azure.storage.queue import QueueClient, AccessPolicy, QueueSasPermissions
215
from datetime import datetime, timedelta
216
217
queue_client = QueueClient.from_connection_string(conn_str, "myqueue")
218
219
# Create stored access policy
220
policy = AccessPolicy(
221
permission=QueueSasPermissions(read=True, add=True, process=True),
222
expiry=datetime.utcnow() + timedelta(days=30),
223
start=datetime.utcnow()
224
)
225
226
# Set the stored access policy
227
queue_client.set_queue_access_policy({"read-write-policy": policy})
228
229
# Generate SAS using stored policy
230
sas_with_policy = generate_queue_sas(
231
account_name="mystorageaccount",
232
queue_name="myqueue",
233
account_key="account_access_key",
234
policy_id="read-write-policy" # Reference stored policy
235
)
236
237
# Client using policy-based SAS
238
policy_client = QueueClient(
239
account_url="https://mystorageaccount.queue.core.windows.net",
240
queue_name="myqueue",
241
credential=sas_with_policy
242
)
243
```
244
245
### IP Restrictions and Security
246
247
```python
248
# Generate SAS with IP restrictions
249
restricted_sas = generate_queue_sas(
250
account_name="mystorageaccount",
251
queue_name="myqueue",
252
account_key="account_access_key",
253
permission=QueueSasPermissions(add=True, process=True),
254
expiry=datetime.utcnow() + timedelta(hours=4),
255
ip="192.168.1.0/24" # Only allow access from this subnet
256
)
257
258
# Generate SAS with specific IP
259
single_ip_sas = generate_queue_sas(
260
account_name="mystorageaccount",
261
queue_name="myqueue",
262
account_key="account_access_key",
263
permission=QueueSasPermissions(read=True),
264
expiry=datetime.utcnow() + timedelta(hours=1),
265
ip="203.0.113.45" # Only allow access from this IP
266
)
267
```
268
269
### Azure AD Authentication Patterns
270
271
```python
272
from azure.identity import (
273
DefaultAzureCredential,
274
ClientSecretCredential,
275
ManagedIdentityCredential,
276
EnvironmentCredential,
277
WorkloadIdentityCredential,
278
AzureCliCredential,
279
ClientCertificateCredential
280
)
281
282
# Default Azure Credential (recommended - tries multiple auth methods)
283
credential = DefaultAzureCredential()
284
service_client = QueueServiceClient(
285
account_url="https://mystorageaccount.queue.core.windows.net",
286
credential=credential
287
)
288
289
# Service Principal Authentication with Client Secret
290
credential = ClientSecretCredential(
291
tenant_id="your_tenant_id",
292
client_id="your_client_id",
293
client_secret="your_client_secret"
294
)
295
296
# Service Principal Authentication with Certificate
297
credential = ClientCertificateCredential(
298
tenant_id="your_tenant_id",
299
client_id="your_client_id",
300
certificate_path="/path/to/certificate.pem"
301
)
302
303
# Managed Identity Authentication (for Azure services)
304
managed_credential = ManagedIdentityCredential()
305
306
# Managed Identity with specific client ID (user-assigned)
307
managed_credential = ManagedIdentityCredential(client_id="your_user_assigned_identity_client_id")
308
309
# Environment-based Authentication (uses environment variables)
310
env_credential = EnvironmentCredential()
311
312
# Workload Identity (for Kubernetes workloads)
313
workload_credential = WorkloadIdentityCredential()
314
315
# Azure CLI Credential (for development)
316
cli_credential = AzureCliCredential()
317
318
service_client = QueueServiceClient(
319
account_url="https://mystorageaccount.queue.core.windows.net",
320
credential=credential
321
)
322
```
323
324
### Named Key Credential Support
325
326
```python
327
from azure.core.credentials import AzureNamedKeyCredential
328
329
# Using Azure Named Key Credential
330
named_key_credential = AzureNamedKeyCredential("account_name", "account_key")
331
332
service_client = QueueServiceClient(
333
account_url="https://mystorageaccount.queue.core.windows.net",
334
credential=named_key_credential
335
)
336
```
337
338
### SAS Credential Support
339
340
```python
341
from azure.core.credentials import AzureSasCredential
342
343
# Using Azure SAS Credential
344
sas_credential = AzureSasCredential("sas_token_string")
345
346
service_client = QueueServiceClient(
347
account_url="https://mystorageaccount.queue.core.windows.net",
348
credential=sas_credential
349
)
350
```
351
352
## Types
353
354
### Permission Types
355
356
```python { .api }
357
class AccountSasPermissions:
358
read: bool # Read account information, list queues
359
write: bool # Write to queues (does not include add/update)
360
delete: bool # Delete queues
361
delete_previous_version: bool # Delete previous blob versions
362
list: bool # List queues in account
363
add: bool # Add messages to queues
364
create: bool # Create queues
365
update: bool # Update message content and visibility
366
process: bool # Get and delete messages
367
tag: bool # Set and get blob tags
368
filter_by_tags: bool # Filter blobs by tags
369
set_immutability_policy: bool # Set/delete immutability policy
370
permanent_delete: bool # Permanently delete blobs
371
372
def __str__(self) -> str: ...
373
374
@classmethod
375
def from_string(cls, permission: str) -> 'AccountSasPermissions': ...
376
377
class QueueSasPermissions:
378
read: bool # Read queue metadata and properties, peek messages
379
add: bool # Add messages to queue
380
update: bool # Update messages in queue (content and visibility)
381
process: bool # Get and delete messages from queue
382
383
def __str__(self) -> str: ...
384
385
@classmethod
386
def from_string(cls, permission: str) -> 'QueueSasPermissions': ...
387
```
388
389
### Resource and Service Types
390
391
```python { .api }
392
class ResourceTypes:
393
service: bool # Service-level operations (list queues, get/set properties)
394
container: bool # Container-level operations (create/delete queues, metadata)
395
object: bool # Object-level operations (message operations)
396
397
def __str__(self) -> str: ...
398
399
@classmethod
400
def from_string(cls, string: str) -> 'ResourceTypes': ...
401
402
class Services:
403
blob: bool # Blob service access
404
queue: bool # Queue service access
405
fileshare: bool # File service access
406
407
def __str__(self) -> str: ...
408
409
@classmethod
410
def from_string(cls, string: str) -> 'Services': ...
411
```
412
413
### Access Policy Types
414
415
```python { .api }
416
class AccessPolicy:
417
permission: Optional[Union[QueueSasPermissions, str]] # Permissions granted
418
expiry: Optional[Union[datetime, str]] # Expiration time
419
start: Optional[Union[datetime, str]] # Start time
420
421
# SAS Token Format Examples:
422
# "sv=2023-01-03&ss=q&srt=sco&sp=rwdlacup&se=2024-01-01T00:00:00Z&st=2023-12-01T00:00:00Z&sip=192.168.1.0/24&spr=https&sig=..."
423
```