0
# ADAL (Azure Active Directory Authentication Library)
1
2
A Python library that makes it easy for applications to authenticate to Azure Active Directory (AAD) in order to access AAD protected web resources. ADAL provides OAuth2 and OpenID Connect authentication flows with comprehensive token management, caching, and refresh capabilities.
3
4
**Note**: This library is legacy. Microsoft recommends migrating to [MSAL Python](https://pypi.org/project/msal/) for new projects.
5
6
## Package Information
7
8
- **Package Name**: adal
9
- **Version**: 1.2.7
10
- **Language**: Python
11
- **Installation**: `pip install adal`
12
- **License**: MIT
13
- **Dependencies**: PyJWT, requests, python-dateutil, cryptography
14
15
## Core Imports
16
17
```python
18
import adal
19
```
20
21
Most common usage pattern:
22
23
```python
24
from adal import AuthenticationContext, TokenCache, AdalError
25
```
26
27
Individual imports:
28
29
```python
30
from adal import (
31
AuthenticationContext,
32
TokenCache,
33
AdalError,
34
set_logging_options,
35
get_logging_options,
36
ADAL_LOGGER_NAME,
37
__version__
38
)
39
```
40
41
## Basic Usage
42
43
```python
44
import adal
45
46
# Create authentication context
47
authority_url = 'https://login.microsoftonline.com/your-tenant-id'
48
context = adal.AuthenticationContext(authority_url)
49
50
# Authenticate using client credentials flow
51
resource = 'https://management.azure.com/'
52
client_id = 'your-client-id'
53
client_secret = 'your-client-secret'
54
55
token = context.acquire_token_with_client_credentials(
56
resource,
57
client_id,
58
client_secret
59
)
60
61
print("Access token:", token['accessToken'])
62
print("Token expires on:", token['expiresOn'])
63
```
64
65
## Architecture
66
67
ADAL follows a context-based architecture centered around the `AuthenticationContext` class:
68
69
- **AuthenticationContext**: Main entry point that manages authentication flows and token acquisition
70
- **TokenCache**: Thread-safe token storage with serialization/deserialization capabilities
71
- **Authority**: Validates and discovers OAuth2 endpoints for Azure AD tenants
72
- **Token Management**: Automatic refresh handling and cache integration
73
74
The library supports multiple OAuth2 flows including authorization code, client credentials, resource owner password credentials, refresh token, certificate-based authentication, and device code flows.
75
76
## Capabilities
77
78
### Authentication Flows
79
80
Core authentication functionality supporting all major OAuth2 flows for Azure Active Directory integration. Includes client credentials, username/password, authorization code, refresh token, certificate-based, and device code authentication methods.
81
82
```python { .api }
83
class AuthenticationContext:
84
def __init__(self, authority, validate_authority=None, cache=None,
85
api_version=None, timeout=None, enable_pii=False,
86
verify_ssl=None, proxies=None): ...
87
88
@property
89
def options(self): ...
90
91
@options.setter
92
def options(self, val): ...
93
94
def acquire_token(self, resource, user_id, client_id): ...
95
def acquire_token_with_username_password(self, resource, username, password, client_id): ...
96
def acquire_token_with_client_credentials(self, resource, client_id, client_secret): ...
97
def acquire_token_with_authorization_code(self, authorization_code, redirect_uri,
98
resource, client_id, client_secret=None,
99
code_verifier=None): ...
100
def acquire_token_with_refresh_token(self, refresh_token, client_id, resource,
101
client_secret=None): ...
102
def acquire_token_with_client_certificate(self, resource, client_id, certificate,
103
thumbprint, public_certificate=None): ...
104
```
105
106
[Authentication Flows](./authentication-flows.md)
107
108
### Device Code Authentication
109
110
Specialized OAuth2 device code flow for applications running on devices without web browsers or with limited input capabilities, such as IoT devices, CLI tools, or applications on smart TVs.
111
112
```python { .api }
113
class AuthenticationContext:
114
def acquire_user_code(self, resource, client_id, language=None): ...
115
def acquire_token_with_device_code(self, resource, user_code_info, client_id): ...
116
def cancel_request_to_get_token_with_device_code(self, user_code_info): ...
117
```
118
119
[Device Code Flow](./device-code-flow.md)
120
121
### Token Caching
122
123
Thread-safe token storage and management with serialization capabilities for persistent caching across application sessions. Supports token lookup, storage, removal, and automatic cleanup.
124
125
```python { .api }
126
class TokenCache:
127
def __init__(self, state=None): ...
128
def find(self, query): ...
129
def add(self, entries): ...
130
def remove(self, entries): ...
131
def serialize(self): ...
132
def deserialize(self, state): ...
133
def read_items(self): ...
134
135
@property
136
def has_state_changed(self): ...
137
```
138
139
[Token Caching](./token-caching.md)
140
141
### Logging and Error Handling
142
143
Comprehensive logging system with PII scrubbing capabilities and custom exception handling for authentication errors. Includes correlation ID support and configurable log levels.
144
145
```python { .api }
146
def set_logging_options(options=None): ...
147
def get_logging_options(): ...
148
149
class AdalError(Exception):
150
def __init__(self, error_msg, error_response=None): ...
151
```
152
153
[Logging and Error Handling](./logging-error-handling.md)
154
155
## Types
156
157
### Authentication Response
158
159
```python { .api }
160
# Return type for all acquire_token_* methods
161
AuthenticationResult = dict[str, Any] # Contains:
162
# "accessToken": str - JWT access token
163
# "refreshToken": str - Refresh token (if available)
164
# "tokenType": str - Token type (usually "Bearer")
165
# "expiresIn": int - Seconds until expiration
166
# "expiresOn": str - ISO 8601 expiration timestamp
167
# "resource": str - Resource URI
168
# "userId": str - User identifier
169
# "userInfo": dict - User profile information
170
```
171
172
### Cache Query
173
174
```python { .api }
175
# Query parameters for TokenCache.find()
176
CacheQuery = dict[str, Any] # Optional keys:
177
# "_clientId": str - OAuth client ID (note underscore prefix)
178
# "userId": str - User identifier
179
# "isMRRT": bool - Match multi-resource refresh tokens
180
```
181
182
### Device Code Response
183
184
```python { .api }
185
# Return type for acquire_user_code()
186
DeviceCodeResult = dict[str, Any] # Contains:
187
# "userCode": str - Code for user to enter
188
# "deviceCode": str - Device code for token requests
189
# "verificationUrl": str - URL where user enters code
190
# "expiresIn": int - Seconds until code expires
191
# "interval": int - Polling interval in seconds
192
# "message": str - Instructions for user
193
```
194
195
### Constants
196
197
```python { .api }
198
__version__: str # Package version: "1.2.7"
199
ADAL_LOGGER_NAME: str # Logger name: "adal-python"
200
```