or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdblob-client.mdblob-types-tiers.mdcontainer-client.mdindex.mdsas-generation.mdservice-client.mdutility-functions.md

sas-generation.mddocs/

0

# Shared Access Signatures

1

2

Generate time-limited, secure access tokens for Azure Storage resources without exposing account keys. SAS tokens enable granular permission control for external access to storage accounts, containers, and blobs.

3

4

## Capabilities

5

6

### Account-Level SAS

7

8

Generate account-level SAS tokens that provide access to multiple storage services and resource types within a storage account.

9

10

```python { .api }

11

def generate_account_sas(account_name: str, account_key: str, resource_types: Union[ResourceTypes, str], permission: Union[AccountSasPermissions, str], expiry: Union[datetime, str], start: Optional[Union[datetime, str]] = None, ip: Optional[str] = None, *, services: Union[Services, str] = Services(blob=True), **kwargs) -> str:

12

"""

13

Generate an account-level shared access signature.

14

15

Args:

16

account_name (str): Storage account name

17

account_key (str): Storage account key

18

resource_types (Union[ResourceTypes, str]): Resource types the SAS can access

19

permission (Union[AccountSasPermissions, str]): Permissions granted by the SAS

20

expiry (Union[datetime, str]): SAS expiration time

21

22

Optional Args:

23

start (Optional[Union[datetime, str]]): SAS start time (default: now)

24

ip (Optional[str]): IP address or range restriction

25

services (Union[Services, str]): Storage services the SAS can access (default: blob service only)

26

27

Returns:

28

str: Account SAS token string

29

"""

30

```

31

32

**Usage Example:**

33

```python

34

from azure.storage.blob import generate_account_sas, ResourceTypes, AccountSasPermissions

35

from datetime import datetime, timedelta

36

37

# Generate account SAS valid for 1 hour

38

sas_token = generate_account_sas(

39

account_name="mystorageaccount",

40

account_key="account_key_here",

41

resource_types=ResourceTypes(service=True, container=True, object=True),

42

permission=AccountSasPermissions(read=True, write=True, list=True),

43

expiry=datetime.utcnow() + timedelta(hours=1),

44

protocol="https"

45

)

46

```

47

48

### Container-Level SAS

49

50

Generate container-level SAS tokens that provide access to a specific container and its blobs.

51

52

```python { .api }

53

def generate_container_sas(account_name: str, container_name: str, account_key=None, user_delegation_key=None, permission=None, expiry=None, start=None, policy_id=None, ip=None, protocol=None, **kwargs) -> str:

54

"""

55

Generate a container-level shared access signature.

56

57

Args:

58

account_name (str): Storage account name

59

container_name (str): Container name

60

account_key (str, optional): Storage account key

61

user_delegation_key (UserDelegationKey, optional): User delegation key for Azure AD auth

62

permission (ContainerSasPermissions, optional): Permissions granted by the SAS

63

expiry (datetime, optional): SAS expiration time

64

start (datetime, optional): SAS start time

65

policy_id (str, optional): Stored access policy identifier

66

ip (str, optional): IP address or range restriction

67

protocol (str, optional): Protocol restriction ('https' or 'https,http')

68

69

Note:

70

Must provide either account_key or user_delegation_key.

71

Must provide either permission/expiry or policy_id.

72

73

Returns:

74

str: Container SAS token string

75

"""

76

```

77

78

**Usage Example:**

79

```python

80

from azure.storage.blob import generate_container_sas, ContainerSasPermissions

81

82

# Generate container SAS with account key

83

sas_token = generate_container_sas(

84

account_name="mystorageaccount",

85

container_name="mycontainer",

86

account_key="account_key_here",

87

permission=ContainerSasPermissions(read=True, write=True, list=True),

88

expiry=datetime.utcnow() + timedelta(hours=2)

89

)

90

91

# Generate container SAS with stored access policy

92

sas_token = generate_container_sas(

93

account_name="mystorageaccount",

94

container_name="mycontainer",

95

account_key="account_key_here",

96

policy_id="my-stored-policy"

97

)

98

```

99

100

### Blob-Level SAS

101

102

Generate blob-level SAS tokens that provide access to a specific blob, including snapshots and versions.

103

104

```python { .api }

105

def generate_blob_sas(account_name: str, container_name: str, blob_name: str, snapshot=None, version_id=None, account_key=None, user_delegation_key=None, permission=None, expiry=None, start=None, policy_id=None, ip=None, protocol=None, **kwargs) -> str:

106

"""

107

Generate a blob-level shared access signature.

108

109

Args:

110

account_name (str): Storage account name

111

container_name (str): Container name

112

blob_name (str): Blob name

113

snapshot (str, optional): Blob snapshot identifier

114

version_id (str, optional): Blob version identifier

115

account_key (str, optional): Storage account key

116

user_delegation_key (UserDelegationKey, optional): User delegation key for Azure AD auth

117

permission (BlobSasPermissions, optional): Permissions granted by the SAS

118

expiry (datetime, optional): SAS expiration time

119

start (datetime, optional): SAS start time

120

policy_id (str, optional): Stored access policy identifier

121

ip (str, optional): IP address or range restriction

122

protocol (str, optional): Protocol restriction ('https' or 'https,http')

123

124

Optional Keyword Args:

125

content_type (str, optional): Response content type override

126

content_encoding (str, optional): Response content encoding override

127

content_language (str, optional): Response content language override

128

content_disposition (str, optional): Response content disposition override

129

cache_control (str, optional): Response cache control override

130

131

Note:

132

Must provide either account_key or user_delegation_key.

133

Must provide either permission/expiry or policy_id.

134

135

Returns:

136

str: Blob SAS token string

137

"""

138

```

139

140

**Usage Example:**

141

```python

142

from azure.storage.blob import generate_blob_sas, BlobSasPermissions

143

144

# Generate blob SAS for read access

145

sas_token = generate_blob_sas(

146

account_name="mystorageaccount",

147

container_name="mycontainer",

148

blob_name="myblob.txt",

149

account_key="account_key_here",

150

permission=BlobSasPermissions(read=True),

151

expiry=datetime.utcnow() + timedelta(hours=1)

152

)

153

154

# Generate blob SAS with response headers override

155

sas_token = generate_blob_sas(

156

account_name="mystorageaccount",

157

container_name="mycontainer",

158

blob_name="document.pdf",

159

account_key="account_key_here",

160

permission=BlobSasPermissions(read=True),

161

expiry=datetime.utcnow() + timedelta(hours=1),

162

content_type="application/pdf",

163

content_disposition="attachment; filename=document.pdf"

164

)

165

```

166

167

## Permission Classes

168

169

### AccountSasPermissions

170

171

Define permissions for account-level SAS tokens across multiple storage services.

172

173

```python { .api }

174

class AccountSasPermissions:

175

"""Account-level SAS permissions."""

176

177

def __init__(self, read=False, write=False, delete=False, list=False, add=False, create=False, update=False, process=False, delete_previous_version=False, tag=False, filter_by_tags=False, **kwargs):

178

"""

179

Initialize account SAS permissions.

180

181

Args:

182

read (bool): Read access to resources

183

write (bool): Write access to resources

184

delete (bool): Delete access to resources

185

list (bool): List access to resources

186

add (bool): Add access to resources

187

create (bool): Create access to resources

188

update (bool): Update access to resources

189

process (bool): Process access to resources

190

delete_previous_version (bool): Delete previous versions

191

tag (bool): Tag access to resources

192

filter_by_tags (bool): Filter by tags access

193

"""

194

195

@classmethod

196

def from_string(cls, permission: str) -> 'AccountSasPermissions':

197

"""Create permissions from permission string (e.g., 'rwdlacup')."""

198

199

def __str__(self) -> str:

200

"""Return permission string representation."""

201

```

202

203

### ContainerSasPermissions

204

205

Define permissions for container-level SAS tokens.

206

207

```python { .api }

208

class ContainerSasPermissions:

209

"""Container-level SAS permissions."""

210

211

def __init__(self, read=False, write=False, delete=False, list=False, add=False, create=False, delete_previous_version=False, tag=False, **kwargs):

212

"""

213

Initialize container SAS permissions.

214

215

Args:

216

read (bool): Read blobs in container

217

write (bool): Write blobs in container

218

delete (bool): Delete blobs in container

219

list (bool): List blobs in container

220

add (bool): Add blobs to container

221

create (bool): Create blobs in container

222

delete_previous_version (bool): Delete previous blob versions

223

tag (bool): Set/get blob tags

224

"""

225

226

@classmethod

227

def from_string(cls, permission: str) -> 'ContainerSasPermissions':

228

"""Create permissions from permission string (e.g., 'rwdl')."""

229

230

def __str__(self) -> str:

231

"""Return permission string representation."""

232

```

233

234

### BlobSasPermissions

235

236

Define permissions for blob-level SAS tokens.

237

238

```python { .api }

239

class BlobSasPermissions:

240

"""Blob-level SAS permissions."""

241

242

def __init__(self, read=False, write=False, delete=False, add=False, create=False, delete_previous_version=False, tag=False, move=False, execute=False, **kwargs):

243

"""

244

Initialize blob SAS permissions.

245

246

Args:

247

read (bool): Read the blob

248

write (bool): Write to the blob

249

delete (bool): Delete the blob

250

add (bool): Add blocks to append blob

251

create (bool): Create the blob

252

delete_previous_version (bool): Delete previous versions

253

tag (bool): Set/get blob tags

254

move (bool): Move/rename the blob

255

execute (bool): Execute the blob (if executable)

256

"""

257

258

@classmethod

259

def from_string(cls, permission: str) -> 'BlobSasPermissions':

260

"""Create permissions from permission string (e.g., 'rwd')."""

261

262

def __str__(self) -> str:

263

"""Return permission string representation."""

264

```

265

266

## Resource Types

267

268

### ResourceTypes

269

270

Specify which resource types an account-level SAS can access.

271

272

```python { .api }

273

class ResourceTypes:

274

"""Resource types for account SAS."""

275

276

def __init__(self, service=False, container=False, object=False, **kwargs):

277

"""

278

Initialize resource types.

279

280

Args:

281

service (bool): Access to service-level operations

282

container (bool): Access to container operations

283

object (bool): Access to blob objects

284

"""

285

286

@classmethod

287

def from_string(cls, resource_types: str) -> 'ResourceTypes':

288

"""Create resource types from string (e.g., 'sco')."""

289

290

def __str__(self) -> str:

291

"""Return resource types string representation."""

292

```

293

294

## User Delegation Keys

295

296

User delegation keys enable SAS generation with Azure Active Directory credentials instead of account keys.

297

298

```python { .api }

299

class UserDelegationKey:

300

"""User delegation key for Azure AD-based SAS."""

301

signed_oid: str # Object ID of the user

302

signed_tid: str # Tenant ID

303

signed_start: datetime # Key validity start time

304

signed_expiry: datetime # Key validity end time

305

signed_service: str # Storage service version

306

signed_version: str # Signed version

307

value: str # Key value for signing

308

```

309

310

**Usage Example:**

311

```python

312

# Get user delegation key from service client (requires Azure AD auth)

313

service_client = BlobServiceClient(account_url, credential=azure_ad_credential)

314

user_delegation_key = service_client.get_user_delegation_key(

315

key_start_time=datetime.utcnow(),

316

key_expiry_time=datetime.utcnow() + timedelta(hours=1)

317

)

318

319

# Use delegation key to generate blob SAS

320

sas_token = generate_blob_sas(

321

account_name="mystorageaccount",

322

container_name="mycontainer",

323

blob_name="myblob.txt",

324

user_delegation_key=user_delegation_key,

325

permission=BlobSasPermissions(read=True),

326

expiry=datetime.utcnow() + timedelta(hours=1)

327

)

328

```

329

330

## SAS Usage Patterns

331

332

### Using SAS Tokens

333

334

SAS tokens can be used in several ways:

335

336

```python

337

# Append to URL as query parameter

338

blob_url_with_sas = f"https://account.blob.core.windows.net/container/blob.txt?{sas_token}"

339

340

# Use with client constructors

341

blob_client = BlobClient.from_blob_url(blob_url_with_sas)

342

343

# Use with AzureSasCredential

344

from azure.core.credentials import AzureSasCredential

345

credential = AzureSasCredential(sas_token)

346

blob_client = BlobClient(account_url, container_name, blob_name, credential=credential)

347

```

348

349

### IP and Protocol Restrictions

350

351

Enhance security by restricting SAS usage to specific IP addresses and protocols:

352

353

```python

354

# Restrict to specific IP range and HTTPS only

355

sas_token = generate_blob_sas(

356

account_name="mystorageaccount",

357

container_name="mycontainer",

358

blob_name="myblob.txt",

359

account_key="account_key_here",

360

permission=BlobSasPermissions(read=True),

361

expiry=datetime.utcnow() + timedelta(hours=1),

362

ip="192.168.1.0/24", # IP range restriction

363

protocol="https" # HTTPS only

364

)

365

```

366

367

### Stored Access Policies

368

369

Use stored access policies for easier SAS management and revocation:

370

371

```python

372

# Create stored access policy on container

373

from azure.storage.blob import AccessPolicy, ContainerSasPermissions

374

375

access_policy = AccessPolicy(

376

permission=ContainerSasPermissions(read=True, write=True),

377

expiry=datetime.utcnow() + timedelta(days=1),

378

start=datetime.utcnow()

379

)

380

381

container_client.set_container_access_policy({

382

"my-policy": access_policy

383

})

384

385

# Generate SAS using stored policy

386

sas_token = generate_container_sas(

387

account_name="mystorageaccount",

388

container_name="mycontainer",

389

account_key="account_key_here",

390

policy_id="my-policy"

391

)

392

```