docs
0
# Authentication and Credentials
1
2
Azure Core provides comprehensive authentication mechanisms supporting OAuth tokens, API keys, and Shared Access Signature (SAS) credentials. The authentication system is designed to work seamlessly with both synchronous and asynchronous Azure SDK clients.
3
4
## Capabilities
5
6
### Token-Based Authentication
7
8
OAuth token authentication using the `TokenCredential` protocol for Azure Active Directory and managed identity authentication.
9
10
```python { .api }
11
from azure.core.credentials import TokenCredential, AccessToken, AccessTokenInfo, TokenRequestOptions
12
from typing import Protocol, Union
13
14
class TokenCredential(Protocol):
15
"""Protocol for OAuth token credential providers."""
16
def get_token(self, *scopes: str, **kwargs) -> AccessToken: ...
17
18
class SupportsTokenInfo(Protocol):
19
"""Protocol for extended token providers with additional token information."""
20
def get_token_info(self, *scopes: str, **kwargs) -> AccessTokenInfo: ...
21
22
TokenProvider = Union[TokenCredential, SupportsTokenInfo]
23
```
24
25
#### Token Types
26
27
```python { .api }
28
from typing import NamedTuple
29
30
class AccessToken(NamedTuple):
31
"""OAuth access token container."""
32
token: str
33
expires_on: int # Unix timestamp
34
35
class AccessTokenInfo:
36
"""Extended access token with additional properties."""
37
def __init__(self, token: str, expires_on: int, **kwargs): ...
38
39
@property
40
def token(self) -> str: ...
41
42
@property
43
def expires_on(self) -> int: ...
44
45
class TokenRequestOptions(TypedDict, total=False):
46
"""Options for token requests."""
47
claims: str
48
tenant_id: str
49
enable_cae: bool
50
```
51
52
### API Key Authentication
53
54
Simple API key-based authentication for services that use API keys instead of OAuth tokens.
55
56
```python { .api }
57
class AzureKeyCredential:
58
"""API key-based credential."""
59
def __init__(self, key: str): ...
60
61
def update(self, key: str) -> None:
62
"""Update the API key."""
63
...
64
65
@property
66
def key(self) -> str: ...
67
```
68
69
### Named Key Credentials
70
71
Authentication using name/key pairs for scenarios requiring both an identifier and secret.
72
73
```python { .api }
74
from typing import NamedTuple
75
76
class AzureNamedKey(NamedTuple):
77
"""Name and key pair container."""
78
name: str
79
key: str
80
81
class AzureNamedKeyCredential:
82
"""Named key pair credential."""
83
def __init__(self, name: str, key: str): ...
84
85
def update(self, name: str, key: str) -> None:
86
"""Update the name and key."""
87
...
88
89
@property
90
def named_key(self) -> AzureNamedKey: ...
91
```
92
93
### SAS Credentials
94
95
Shared Access Signature authentication for Azure Storage and other services supporting SAS tokens.
96
97
```python { .api }
98
class AzureSasCredential:
99
"""Shared Access Signature credential."""
100
def __init__(self, signature: str): ...
101
102
def update(self, signature: str) -> None:
103
"""Update the SAS token."""
104
...
105
106
@property
107
def signature(self) -> str: ...
108
```
109
110
### Async Token Authentication
111
112
Asynchronous versions of token credential protocols for async Azure SDK clients.
113
114
```python { .api }
115
from azure.core.credentials_async import AsyncTokenCredential, AsyncSupportsTokenInfo
116
117
class AsyncTokenCredential(Protocol):
118
"""Async protocol for OAuth token credential providers."""
119
async def get_token(self, *scopes: str, **kwargs) -> AccessToken: ...
120
121
class AsyncSupportsTokenInfo(Protocol):
122
"""Async protocol for extended token providers."""
123
async def get_token_info(self, *scopes: str, **kwargs) -> AccessTokenInfo: ...
124
```
125
126
## Usage Examples
127
128
### Basic Token Authentication
129
130
```python
131
from azure.core.credentials import TokenCredential
132
from azure.core import PipelineClient
133
from azure.core.pipeline.policies import BearerTokenCredentialPolicy
134
135
# Assume you have a token credential from azure-identity
136
# from azure.identity import DefaultAzureCredential
137
# credential = DefaultAzureCredential()
138
139
# Create pipeline with token authentication
140
policies = [BearerTokenCredentialPolicy(credential, "https://management.azure.com/.default")]
141
client = PipelineClient(base_url="https://management.azure.com", policies=policies)
142
```
143
144
### API Key Authentication
145
146
```python
147
from azure.core.credentials import AzureKeyCredential
148
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
149
150
# Create API key credential
151
credential = AzureKeyCredential("your-api-key")
152
153
# Use in pipeline policy
154
policy = AzureKeyCredentialPolicy(credential, "X-API-Key")
155
156
# Update key when needed
157
credential.update("new-api-key")
158
```
159
160
### SAS Authentication
161
162
```python
163
from azure.core.credentials import AzureSasCredential
164
from azure.core.pipeline.policies import AzureSasCredentialPolicy
165
166
# Create SAS credential
167
sas_token = "?sv=2020-04-08&sr=c&si=policy&sig=signature"
168
credential = AzureSasCredential(sas_token)
169
170
# Use in pipeline policy
171
policy = AzureSasCredentialPolicy(credential)
172
173
# Update SAS token when needed
174
credential.update("new-sas-token")
175
```
176
177
### Async Token Authentication
178
179
```python
180
import asyncio
181
from azure.core.credentials_async import AsyncTokenCredential
182
from azure.core import AsyncPipelineClient
183
184
async def authenticate_async():
185
# Assume you have an async token credential
186
# from azure.identity.aio import DefaultAzureCredential
187
# credential = DefaultAzureCredential()
188
189
# Use with async pipeline client
190
client = AsyncPipelineClient(base_url="https://api.example.com")
191
192
# Get token asynchronously
193
token = await credential.get_token("https://api.example.com/.default")
194
print(f"Token expires at: {token.expires_on}")
195
196
# asyncio.run(authenticate_async())
197
```
198
199
### Custom Token Request Options
200
201
```python
202
from azure.core.credentials import TokenRequestOptions
203
204
# Request token with specific options
205
token_options: TokenRequestOptions = {
206
"claims": '{"access_token": {"xms_cc": {"values": ["cp1"]}}}',
207
"tenant_id": "specific-tenant-id",
208
"enable_cae": True
209
}
210
211
# Most credential implementations support passing these options
212
# token = credential.get_token("scope", **token_options)
213
```
214
215
## Authentication Pipeline Policies
216
217
Azure Core provides pipeline policies that automatically handle authentication for different credential types.
218
219
### Bearer Token Policy
220
221
```python { .api }
222
from azure.core.pipeline.policies import BearerTokenCredentialPolicy, AsyncBearerTokenCredentialPolicy
223
224
class BearerTokenCredentialPolicy(HTTPPolicy):
225
"""Policy for Bearer token authentication."""
226
def __init__(self, credential: TokenCredential, *scopes: str, **kwargs): ...
227
228
class AsyncBearerTokenCredentialPolicy(AsyncHTTPPolicy):
229
"""Async policy for Bearer token authentication."""
230
def __init__(self, credential: AsyncTokenCredential, *scopes: str, **kwargs): ...
231
```
232
233
### API Key Policy
234
235
```python { .api }
236
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
237
238
class AzureKeyCredentialPolicy(HTTPPolicy):
239
"""Policy for API key authentication."""
240
def __init__(self, credential: AzureKeyCredential, name: str, **kwargs): ...
241
```
242
243
### SAS Policy
244
245
```python { .api }
246
from azure.core.pipeline.policies import AzureSasCredentialPolicy
247
248
class AzureSasCredentialPolicy(HTTPPolicy):
249
"""Policy for SAS authentication."""
250
def __init__(self, credential: AzureSasCredential, **kwargs): ...
251
```
252
253
## Best Practices
254
255
### Credential Management
256
257
- Store credentials securely and never hard-code them in source code
258
- Use Azure Key Vault or environment variables for credential storage
259
- Rotate credentials regularly and update them using the `update()` methods
260
- Use managed identities when running in Azure environments
261
262
### Token Caching
263
264
- Token credentials automatically handle token caching and renewal
265
- Tokens are cached until near expiration to minimize authentication requests
266
- Multiple clients can share the same credential instance for efficiency
267
268
### Error Handling
269
270
- Handle `ClientAuthenticationError` for authentication failures
271
- Implement retry logic for transient authentication errors
272
- Monitor token expiration and handle renewal failures gracefully
273
274
### Async Considerations
275
276
- Use async credential types with async pipeline clients
277
- Properly handle async context management for credential cleanup
278
- Be aware of token refresh timing in long-running async operations