or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-msal

Microsoft Authentication Library for Python enabling OAuth2/OIDC authentication with Microsoft identity platform

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/msal@1.33.x

To install, run

npx @tessl/cli install tessl/pypi-msal@1.33.0

0

# MSAL - Microsoft Authentication Library

1

2

The Microsoft Authentication Library (MSAL) for Python enables your app to access the Microsoft Cloud by supporting authentication of users with Microsoft Azure Active Directory accounts (AAD), Microsoft Accounts (MSA), External identities, and Azure AD B2C accounts using industry standard OAuth2 and OpenID Connect protocols.

3

4

MSAL Python provides both public client applications for desktop/mobile scenarios and confidential client applications for server-side scenarios, with automatic token caching, refresh capabilities, broker support for enhanced security, and extensive configuration options for different authentication flows.

5

6

## Package Information

7

8

- **Package Name**: msal

9

- **Language**: Python

10

- **Installation**: `pip install msal`

11

- **Optional broker support**: `pip install msal[broker]`

12

13

## Core Imports

14

15

```python

16

import msal

17

```

18

19

Common imports for different application types:

20

21

```python

22

from msal import PublicClientApplication, ConfidentialClientApplication

23

```

24

25

Token caching imports:

26

27

```python

28

from msal import TokenCache, SerializableTokenCache

29

```

30

31

Managed identity imports:

32

33

```python

34

from msal import ManagedIdentityClient, SystemAssignedManagedIdentity, UserAssignedManagedIdentity

35

```

36

37

Version information:

38

39

```python

40

import msal

41

print(msal.__version__) # "1.33.0"

42

```

43

44

## Basic Usage

45

46

### Public Client Application (Desktop/Mobile)

47

48

```python

49

import msal

50

51

# Create a public client application

52

app = msal.PublicClientApplication(

53

client_id="your-client-id",

54

authority="https://login.microsoftonline.com/your-tenant-id"

55

)

56

57

# Get accounts from cache

58

accounts = app.get_accounts()

59

60

# Try silent authentication first

61

result = None

62

if accounts:

63

result = app.acquire_token_silent(

64

scopes=["User.Read"],

65

account=accounts[0]

66

)

67

68

# If silent fails, use interactive authentication

69

if not result:

70

result = app.acquire_token_interactive(

71

scopes=["User.Read"]

72

)

73

74

if "access_token" in result:

75

print("Authentication successful!")

76

print(f"Access token: {result['access_token'][:20]}...")

77

else:

78

print(f"Authentication failed: {result.get('error_description')}")

79

```

80

81

### Confidential Client Application (Server-side)

82

83

```python

84

import msal

85

86

# Create a confidential client application

87

app = msal.ConfidentialClientApplication(

88

client_id="your-client-id",

89

client_credential="your-client-secret",

90

authority="https://login.microsoftonline.com/your-tenant-id"

91

)

92

93

# Acquire token for client (Client Credentials flow)

94

result = app.acquire_token_for_client(

95

scopes=["https://graph.microsoft.com/.default"]

96

)

97

98

if "access_token" in result:

99

print("Authentication successful!")

100

access_token = result["access_token"]

101

else:

102

print(f"Authentication failed: {result.get('error_description')}")

103

```

104

105

## Architecture

106

107

MSAL Python follows the OAuth2/OIDC protocol specifications with Microsoft identity platform extensions:

108

109

- **Application Types**: PublicClientApplication for native apps, ConfidentialClientApplication for server apps

110

- **Token Management**: Automatic caching, refresh, and persistence with TokenCache/SerializableTokenCache

111

- **Authentication Flows**: Interactive, device flow, authorization code, username/password, client credentials, on-behalf-of

112

- **Security Features**: Proof-of-Possession tokens, broker integration, certificate-based authentication

113

- **Azure Integration**: Managed identity support, Azure AD B2C, multi-tenant applications

114

115

The library handles protocol complexities like token refresh, scope validation, and error handling while providing a simple, consistent API across different authentication scenarios.

116

117

## Capabilities

118

119

### Public Client Applications

120

121

Desktop and mobile application authentication with interactive browser flows, device code authentication for browserless devices, and optional broker integration for enhanced security through device identity.

122

123

```python { .api }

124

class PublicClientApplication(ClientApplication):

125

def __init__(

126

self,

127

client_id: str,

128

client_credential=None,

129

*,

130

enable_broker_on_windows=None,

131

enable_broker_on_mac=None,

132

enable_broker_on_linux=None,

133

enable_broker_on_wsl=None,

134

**kwargs

135

): ...

136

137

def acquire_token_interactive(

138

self,

139

scopes: list,

140

prompt=None,

141

login_hint=None,

142

domain_hint=None,

143

claims_challenge=None,

144

timeout=None,

145

port=None,

146

extra_scopes_to_consent=None,

147

max_age=None,

148

parent_window_handle=None,

149

on_before_launching_ui=None,

150

auth_scheme=None,

151

**kwargs

152

): ...

153

154

def initiate_device_flow(self, scopes=None, **kwargs): ...

155

156

def acquire_token_by_device_flow(self, flow, claims_challenge=None, **kwargs): ...

157

```

158

159

[Public Client Applications](./public-client.md)

160

161

### Confidential Client Applications

162

163

Server-side web application authentication with client credentials flow for service-to-service authentication, authorization code flow for web apps, and on-behalf-of flow for middle-tier services acting on behalf of users.

164

165

```python { .api }

166

class ConfidentialClientApplication(ClientApplication):

167

def __init__(

168

self,

169

client_id: str,

170

client_credential,

171

authority=None,

172

**kwargs

173

): ...

174

175

def acquire_token_for_client(

176

self,

177

scopes: list,

178

claims_challenge=None,

179

**kwargs

180

): ...

181

182

def acquire_token_on_behalf_of(

183

self,

184

user_assertion: str,

185

scopes: list,

186

claims_challenge=None,

187

**kwargs

188

): ...

189

```

190

191

[Confidential Client Applications](./confidential-client.md)

192

193

### Token Caching

194

195

Unified token cache system supporting both in-memory caching for single-session applications and persistent caching for multi-session scenarios. Includes automatic token refresh, account management, and cross-application token sharing.

196

197

```python { .api }

198

class TokenCache:

199

def __init__(self): ...

200

201

def find(

202

self,

203

credential_type: str,

204

target=None,

205

query=None,

206

now=None

207

) -> list: ...

208

209

def add(self, event: dict, now=None): ...

210

211

class SerializableTokenCache(TokenCache):

212

def serialize(self) -> str: ...

213

214

def deserialize(self, state: str): ...

215

```

216

217

[Token Caching](./token-cache.md)

218

219

### Common Authentication Flows

220

221

Shared authentication functionality including silent token acquisition from cache, authorization code flow initiation and completion, username/password authentication, refresh token handling, and account management across all application types.

222

223

```python { .api }

224

class ClientApplication:

225

def acquire_token_silent(

226

self,

227

scopes: list,

228

account,

229

authority=None,

230

force_refresh=False,

231

claims_challenge=None,

232

**kwargs

233

): ...

234

235

def initiate_auth_code_flow(

236

self,

237

scopes: list,

238

redirect_uri=None,

239

state=None,

240

prompt=None,

241

login_hint=None,

242

**kwargs

243

): ...

244

245

def acquire_token_by_auth_code_flow(

246

self,

247

auth_code_flow: dict,

248

auth_response: dict,

249

scopes=None,

250

**kwargs

251

): ...

252

253

def acquire_token_by_username_password(

254

self,

255

username: str,

256

password: str,

257

scopes: list,

258

claims_challenge=None,

259

auth_scheme=None,

260

**kwargs

261

): ...

262

263

def acquire_token_by_refresh_token(

264

self,

265

refresh_token: str,

266

scopes: list,

267

**kwargs

268

): ...

269

270

def get_accounts(self, username=None) -> list: ...

271

272

def remove_account(self, account): ...

273

```

274

275

[Common Authentication Flows](./common-auth-flows.md)

276

277

### Azure Managed Identity

278

279

Azure managed identity authentication for virtual machines, container instances, and other Azure services. Supports both system-assigned identities (automatically created with the resource) and user-assigned identities (standalone resources assigned to multiple services).

280

281

```python { .api }

282

class ManagedIdentityClient:

283

def __init__(

284

self,

285

managed_identity,

286

http_client=None,

287

token_cache=None,

288

**kwargs

289

): ...

290

291

def acquire_token_for_client(

292

self,

293

resource: str,

294

claims_challenge=None

295

): ...

296

297

class SystemAssignedManagedIdentity:

298

def __init__(self): ...

299

300

class UserAssignedManagedIdentity:

301

def __init__(

302

self,

303

client_id=None,

304

object_id=None,

305

resource_id=None

306

): ...

307

```

308

309

[Azure Managed Identity](./managed-identity.md)

310

311

### Security and Advanced Features

312

313

Advanced security features including Proof-of-Possession (PoP) token authentication for enhanced security, certificate-based authentication with X.509 certificates, custom authentication schemes, and comprehensive error handling with detailed error information.

314

315

```python { .api }

316

class PopAuthScheme:

317

def __init__(

318

self,

319

http_method: str = None,

320

url: str = None,

321

nonce: str = None

322

): ...

323

324

def extract_certs(public_cert_content: str) -> list: ...

325

326

class Prompt:

327

NONE = "none"

328

LOGIN = "login"

329

CONSENT = "consent"

330

SELECT_ACCOUNT = "select_account"

331

CREATE = "create"

332

```

333

334

[Security and Advanced Features](./security-advanced.md)

335

336

## Types

337

338

```python { .api }

339

# Authentication result dictionary

340

AuthResult = dict # Contains 'access_token', 'token_type', 'expires_in', etc.

341

342

# Account dictionary from cache

343

Account = dict # Contains 'home_account_id', 'environment', 'username', etc.

344

345

# Auth code flow state dictionary

346

AuthCodeFlow = dict # Contains 'auth_uri', 'state', 'code_verifier', etc.

347

348

# Device flow state dictionary

349

DeviceFlow = dict # Contains 'device_code', 'user_code', 'verification_uri', etc.

350

```

351

352

## Exception Types

353

354

```python { .api }

355

class MsalError(Exception):

356

"""Base exception for MSAL errors."""

357

358

class MsalServiceError(MsalError):

359

"""Exception for errors from identity service."""

360

def __init__(self, *args, error: str, error_description: str, **kwargs): ...

361

362

class IdTokenError(RuntimeError):

363

"""Exception for ID token validation errors."""

364

365

class IdTokenIssuerError(IdTokenError):

366

"""Exception for ID token issuer validation errors."""

367

368

class IdTokenAudienceError(IdTokenError):

369

"""Exception for ID token audience validation errors."""

370

371

class IdTokenNonceError(IdTokenError):

372

"""Exception for ID token nonce validation errors."""

373

374

class BrowserInteractionTimeoutError(RuntimeError):

375

"""Exception for browser interaction timeout."""

376

377

class ManagedIdentityError(ValueError):

378

"""Exception for managed identity errors."""

379

380

class ArcPlatformNotSupportedError(ManagedIdentityError):

381

"""Exception for unsupported Azure Arc platforms."""

382

```