or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mddirectory-services.mdemail-calendar.mdindex.mdonedrive-files.mdsharepoint-sites.mdteams.md

authentication.mddocs/

0

# Authentication & Client Setup

1

2

Comprehensive authentication support for Microsoft 365 services with multiple authentication flows designed for enterprise environments. The library supports both modern OAuth2 flows for Microsoft Graph and legacy authentication methods for SharePoint REST API.

3

4

## Capabilities

5

6

### GraphClient Authentication

7

8

Microsoft Graph API client with support for OAuth2 flows including client credentials, certificate-based authentication, interactive authentication, and device code flow.

9

10

```python { .api }

11

class GraphClient:

12

def __init__(self, tenant: str = None, scopes: List[str] = None, token_cache=None, environment=None):

13

"""

14

Initialize Microsoft Graph client.

15

16

Args:

17

tenant (str, optional): Azure AD tenant ID or domain name

18

scopes (List[str], optional): OAuth2 scopes to request

19

token_cache (optional): Token cache for storing authentication tokens

20

environment (AzureEnvironment, optional): Azure cloud environment

21

"""

22

23

def with_client_secret(self, client_id: str, client_secret: str) -> 'GraphClient':

24

"""

25

Authenticate using client credentials flow (app-only authentication).

26

27

Args:

28

client_id (str): Azure AD application client ID

29

client_secret (str): Azure AD application client secret

30

31

Returns:

32

GraphClient: Self for method chaining

33

"""

34

35

def with_certificate(self, client_id: str, thumbprint: str, private_key: str) -> 'GraphClient':

36

"""

37

Authenticate using certificate-based authentication.

38

39

Args:

40

client_id (str): Azure AD application client ID

41

thumbprint (str): Certificate thumbprint (SHA-1 hash)

42

private_key (str): PEM-formatted private key

43

44

Returns:

45

GraphClient: Self for method chaining

46

"""

47

48

def with_token_interactive(self, client_id: str, username: str = None) -> 'GraphClient':

49

"""

50

Authenticate using interactive browser flow.

51

52

Args:

53

client_id (str): Azure AD application client ID

54

username (str, optional): Username hint for login

55

56

Returns:

57

GraphClient: Self for method chaining

58

"""

59

60

def with_username_and_password(self, client_id: str, username: str, password: str) -> 'GraphClient':

61

"""

62

Authenticate using username and password (resource owner password credentials flow).

63

64

Args:

65

client_id (str): Azure AD application client ID

66

username (str): User's username or email

67

password (str): User's password

68

69

Returns:

70

GraphClient: Self for method chaining

71

"""

72

73

def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'GraphClient':

74

"""

75

Authenticate using device code flow for devices without web browsers.

76

77

Args:

78

tenant (str): Azure AD tenant ID or domain name

79

client_id (str): Azure AD application client ID

80

scopes (List[str], optional): OAuth2 scopes to request

81

82

Returns:

83

GraphClient: Self for method chaining

84

"""

85

86

def with_access_token(self, token_func: Callable[[], dict]) -> 'GraphClient':

87

"""

88

Authenticate using custom token provider callback.

89

90

Args:

91

token_func (Callable): Function that returns token dictionary

92

93

Returns:

94

GraphClient: Self for method chaining

95

"""

96

```

97

98

### SharePoint ClientContext Authentication

99

100

SharePoint REST API client with support for modern OAuth2 flows and legacy authentication methods including NTLM and digest authentication.

101

102

```python { .api }

103

class ClientContext:

104

def __init__(self, site_url: str):

105

"""

106

Initialize SharePoint client context.

107

108

Args:

109

site_url (str): SharePoint site URL

110

"""

111

112

def with_client_credentials(self, client_id: str, client_secret: str) -> 'ClientContext':

113

"""

114

Authenticate using OAuth2 client credentials flow.

115

116

Args:

117

client_id (str): Azure AD application client ID

118

client_secret (str): Azure AD application client secret

119

120

Returns:

121

ClientContext: Authenticated SharePoint client

122

"""

123

124

def with_client_certificate(self, tenant: str, client_id: str, thumbprint: str, cert_path: str = None, private_key: str = None, scopes: List[str] = None, passphrase: str = None) -> 'ClientContext':

125

"""

126

Authenticate using certificate-based authentication.

127

128

Args:

129

tenant (str): Azure AD tenant ID or domain name

130

client_id (str): Azure AD application client ID

131

thumbprint (str): Certificate thumbprint (SHA-1 hash)

132

cert_path (str, optional): Path to certificate file

133

private_key (str, optional): PEM-formatted private key

134

scopes (List[str], optional): OAuth2 scopes to request

135

passphrase (str, optional): Certificate passphrase if encrypted

136

137

Returns:

138

ClientContext: Authenticated SharePoint client

139

"""

140

141

def with_interactive(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext':

142

"""

143

Authenticate using interactive browser flow.

144

145

Args:

146

tenant (str): Azure AD tenant ID or domain name

147

client_id (str): Azure AD application client ID

148

scopes (List[str], optional): OAuth2 scopes to request

149

150

Returns:

151

ClientContext: Authenticated SharePoint client

152

"""

153

154

def with_user_credentials(self, username: str, password: str) -> 'ClientContext':

155

"""

156

Authenticate using username and password.

157

158

Args:

159

username (str): User's username or email

160

password (str): User's password

161

162

Returns:

163

ClientContext: Authenticated SharePoint client

164

"""

165

166

def with_ntlm(self, username: str, password: str) -> 'ClientContext':

167

"""

168

Authenticate using NTLM authentication (for on-premises SharePoint).

169

170

Args:

171

username (str): Domain\\username or username@domain

172

password (str): User's password

173

174

Returns:

175

ClientContext: Authenticated SharePoint client

176

"""

177

178

def with_digest(self, username: str, password: str) -> 'ClientContext':

179

"""

180

Authenticate using digest authentication.

181

182

Args:

183

username (str): User's username

184

password (str): User's password

185

186

Returns:

187

ClientContext: Authenticated SharePoint client

188

"""

189

190

def with_access_token(self, token_func: Callable[[], dict]) -> 'ClientContext':

191

"""

192

Authenticate using custom token provider callback.

193

194

Args:

195

token_func (Callable): Function that returns token dictionary

196

197

Returns:

198

ClientContext: Authenticated SharePoint client

199

"""

200

201

def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext':

202

"""

203

Authenticate using device code flow for devices without web browsers.

204

205

Args:

206

tenant (str): Azure AD tenant ID or domain name

207

client_id (str): Azure AD application client ID

208

scopes (List[str], optional): OAuth2 scopes to request

209

210

Returns:

211

ClientContext: Authenticated SharePoint client

212

"""

213

214

def with_credentials(self, credentials: Union[UserCredential, ClientCredential]) -> 'ClientContext':

215

"""

216

Authenticate using credential object.

217

218

Args:

219

credentials (Union[UserCredential, ClientCredential]): Pre-configured credential object

220

221

Returns:

222

ClientContext: Authenticated SharePoint client

223

"""

224

```

225

226

### Authentication Context Management

227

228

Core authentication infrastructure supporting multiple credential types and token management.

229

230

```python { .api }

231

class AuthenticationContext:

232

"""Core authentication management with support for multiple auth flows."""

233

234

def __init__(self, authority_url: str):

235

"""

236

Initialize authentication context.

237

238

Args:

239

authority_url (str): Azure AD authority URL

240

"""

241

242

def acquire_token_for_client(self, client_id: str, client_secret: str, resource: str) -> Dict[str, Any]:

243

"""

244

Acquire token using client credentials flow.

245

246

Returns:

247

Dict containing access_token, token_type, expires_in

248

"""

249

250

class ClientCredential:

251

"""Client credentials authentication."""

252

253

def __init__(self, client_id: str, client_secret: str):

254

"""

255

Initialize client credentials.

256

257

Args:

258

client_id (str): Application client ID

259

client_secret (str): Application client secret

260

"""

261

262

class UserCredential:

263

"""User credentials authentication."""

264

265

def __init__(self, username: str, password: str):

266

"""

267

Initialize user credentials.

268

269

Args:

270

username (str): User's username or email

271

password (str): User's password

272

"""

273

274

class CertificateCredential:

275

"""Certificate-based authentication."""

276

277

def __init__(self, client_id: str, thumbprint: str, private_key: str):

278

"""

279

Initialize certificate credentials.

280

281

Args:

282

client_id (str): Application client ID

283

thumbprint (str): Certificate thumbprint

284

private_key (str): PEM-formatted private key

285

"""

286

287

class InteractiveCredential:

288

"""Interactive browser authentication."""

289

290

def __init__(self, client_id: str, tenant: str = None):

291

"""

292

Initialize interactive credentials.

293

294

Args:

295

client_id (str): Application client ID

296

tenant (str, optional): Tenant ID or domain

297

"""

298

```

299

300

### Azure Environment Configuration

301

302

Configuration for different Azure cloud environments with appropriate endpoints and settings.

303

304

```python { .api }

305

class AzureEnvironment:

306

"""Azure cloud environment configuration with appropriate endpoints."""

307

308

@property

309

def authority_host_url(self) -> str:

310

"""Azure AD authority host URL for the environment."""

311

312

@property

313

def graph_endpoint_url(self) -> str:

314

"""Microsoft Graph API endpoint URL for the environment."""

315

316

@property

317

def sharepoint_principal_id(self) -> str:

318

"""SharePoint service principal ID for the environment."""

319

320

# Pre-configured environments

321

AzureEnvironment.Global: AzureEnvironment # Azure Global cloud (default)

322

AzureEnvironment.China: AzureEnvironment # Azure China (21Vianet)

323

AzureEnvironment.USGovernment: AzureEnvironment # Azure US Government

324

AzureEnvironment.Germany: AzureEnvironment # Azure Germany

325

```

326

327

## Usage Examples

328

329

### Client Credentials Flow (Server-to-Server)

330

331

```python

332

from office365.graph_client import GraphClient

333

from office365.sharepoint.client_context import ClientContext

334

335

# Microsoft Graph API

336

graph_client = GraphClient(tenant="your-tenant-id").with_client_secret(

337

client_id="your-app-id",

338

client_secret="your-app-secret"

339

)

340

341

# SharePoint REST API

342

sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_client_credentials(

343

client_id="your-app-id",

344

client_secret="your-app-secret"

345

)

346

```

347

348

### Certificate-Based Authentication

349

350

```python

351

# Load certificate

352

with open("private_key.pem", "r") as key_file:

353

private_key = key_file.read()

354

355

# Microsoft Graph with certificate

356

graph_client = GraphClient(tenant="your-tenant-id").with_certificate(

357

client_id="your-app-id",

358

thumbprint="certificate-thumbprint",

359

private_key=private_key

360

)

361

362

# SharePoint with certificate

363

sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_client_certificate(

364

tenant="your-tenant-id",

365

client_id="your-app-id",

366

thumbprint="certificate-thumbprint",

367

private_key=private_key

368

)

369

```

370

371

### Interactive Authentication

372

373

```python

374

# Interactive login for Microsoft Graph

375

graph_client = GraphClient(tenant="your-tenant-id").with_token_interactive(

376

client_id="your-app-id",

377

username="user@domain.com" # Optional username hint

378

)

379

380

# Interactive login for SharePoint

381

sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_interactive(

382

tenant="your-tenant-id",

383

client_id="your-app-id"

384

)

385

```

386

387

### Username/Password Authentication

388

389

```python

390

# Microsoft Graph with user credentials

391

graph_client = GraphClient(tenant="your-tenant-id").with_username_and_password(

392

client_id="your-app-id",

393

username="user@domain.com",

394

password="user-password"

395

)

396

397

# SharePoint with user credentials

398

sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_user_credentials(

399

username="user@domain.com",

400

password="user-password"

401

)

402

```

403

404

### Custom Token Provider

405

406

```python

407

def custom_token_provider():

408

# Your custom logic to acquire token

409

return {

410

"access_token": "your-access-token",

411

"token_type": "Bearer",

412

"expires_in": 3600

413

}

414

415

# Use custom token provider

416

graph_client = GraphClient().with_token_callback(custom_token_provider)

417

```

418

419

## Types

420

421

```python { .api }

422

from typing import Dict, Any, Callable, List, Optional

423

424

class ClientRequestException(Exception):

425

"""Exception raised for API request errors."""

426

427

def __init__(self, message: str, response: Dict[str, Any] = None):

428

"""

429

Initialize request exception.

430

431

Args:

432

message (str): Error message

433

response (Dict, optional): HTTP response details

434

"""

435

436

class RequestOptions:

437

"""Configuration options for HTTP requests."""

438

439

def __init__(self):

440

self.headers: Dict[str, str] = {}

441

self.timeout: int = 30

442

self.retry_count: int = 3

443

self.stream: bool = False

444

445

class ClientResult:

446

"""Container for API response data."""

447

448

def __init__(self, value: Any = None):

449

self.value: Any = value

450

```