or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-oauthlib

A comprehensive Python library for implementing OAuth 1.0 and OAuth 2.0 authentication protocols

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/oauthlib@3.3.x

To install, run

npx @tessl/cli install tessl/pypi-oauthlib@3.3.0

0

# Types OAuthlib

1

2

Type stubs for oauthlib - a comprehensive Python library for implementing OAuth 1.0 and OAuth 2.0 authentication protocols. This package provides complete type definitions enabling static type checking for OAuth-enabled applications, authentication servers, and API integrations.

3

4

## Package Information

5

6

- **Package Name**: types-oauthlib

7

- **Language**: Python

8

- **Installation**: `pip install types-oauthlib`

9

- **Requires**: oauthlib library (`pip install oauthlib`)

10

11

## Core Imports

12

13

```python

14

import oauthlib

15

from oauthlib import oauth1, oauth2, openid, common

16

17

# Debug functions

18

from oauthlib import set_debug, get_debug

19

```

20

21

OAuth 1.0 specific imports:

22

23

```python

24

from oauthlib.oauth1 import Client, RequestValidator

25

from oauthlib.oauth1 import AccessTokenEndpoint, AuthorizationEndpoint, RequestTokenEndpoint

26

```

27

28

OAuth 2.0 specific imports:

29

30

```python

31

from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient

32

from oauthlib.oauth2 import AuthorizationEndpoint, TokenEndpoint, ResourceEndpoint

33

from oauthlib.oauth2 import RequestValidator, BearerToken

34

```

35

36

OpenID Connect specific imports:

37

38

```python

39

from oauthlib.openid import RequestValidator, Server, UserInfoEndpoint

40

```

41

42

## Basic Usage

43

44

### OAuth 2.0 Client Example

45

46

```python

47

from oauthlib.oauth2 import WebApplicationClient

48

from oauthlib.common import generate_token

49

import requests

50

51

# Create OAuth 2.0 client

52

client = WebApplicationClient('your-client-id')

53

54

# Prepare authorization request

55

authorization_url = 'https://auth.example.com/authorize'

56

url, headers, body = client.prepare_authorization_request(

57

authorization_url,

58

redirect_url='https://your-app.com/callback',

59

scope=['read', 'write'],

60

state=generate_token()

61

)

62

63

# User visits the authorization URL and gets redirected back with code

64

# Exchange authorization code for access token

65

token_url = 'https://auth.example.com/token'

66

url, headers, body = client.prepare_token_request(

67

token_url,

68

authorization_response=callback_url,

69

redirect_url='https://your-app.com/callback'

70

)

71

72

# Make token request

73

token_response = requests.post(url, headers=headers, data=body)

74

client.parse_request_body_response(token_response.text)

75

76

# Use access token to make API requests

77

url, headers, body = client.add_token('https://api.example.com/data')

78

api_response = requests.get(url, headers=headers)

79

```

80

81

### OAuth 2.0 Server Example

82

83

```python

84

from oauthlib.oauth2 import WebApplicationServer, RequestValidator

85

86

class MyRequestValidator(RequestValidator):

87

def validate_client_id(self, client_id, request, *args, **kwargs):

88

# Validate the client_id

89

return client_id in valid_clients

90

91

def authenticate_client(self, request, *args, **kwargs):

92

# Authenticate the client

93

return request.client_id in authenticated_clients

94

95

def save_authorization_code(self, client_id, code, request, *args, **kwargs):

96

# Store authorization code

97

store_code(client_id, code, request)

98

99

# Create OAuth 2.0 server

100

validator = MyRequestValidator()

101

server = WebApplicationServer(validator)

102

103

# Handle authorization request

104

headers, body, status = server.create_authorization_response(

105

uri='https://your-server.com/authorize?response_type=code&client_id=client&redirect_uri=callback',

106

http_method='GET',

107

credentials={'user_id': 'user123'}

108

)

109

```

110

111

## Architecture

112

113

The oauthlib type stubs are organized into several key modules that mirror the OAuth specification hierarchy:

114

115

- **Common Module**: Shared utilities, request handling, and base types used across all OAuth implementations

116

- **OAuth 1.0 Module**: Complete RFC 5849 implementation with clients, endpoints, signature methods, and validation

117

- **OAuth 2.0 Module**: Complete RFC 6749 implementation with multiple client types, server endpoints, grant types, and token handling

118

- **Device Flow Extension**: RFC 8628 device authorization grant for input-constrained devices

119

- **OpenID Connect Module**: OpenID Connect extension providing identity layer on top of OAuth 2.0

120

121

This modular architecture enables developers to use specific OAuth flows while maintaining type safety and IDE support throughout the authentication process.

122

123

## Capabilities

124

125

### OAuth 1.0 Implementation

126

127

Complete OAuth 1.0 (RFC 5849) client and server implementation with signature methods, request/access token flows, and protected resource access. Supports HMAC-SHA1, RSA-SHA1, and PLAINTEXT signature methods.

128

129

```python { .api }

130

class Client:

131

def __init__(

132

self,

133

client_key: str,

134

client_secret: str | None = None,

135

resource_owner_key=None,

136

resource_owner_secret=None,

137

callback_uri=None,

138

signature_method: str = "HMAC-SHA1",

139

signature_type: str = "AUTH_HEADER",

140

rsa_key=None,

141

verifier=None,

142

realm=None,

143

encoding: str = "utf-8",

144

decoding=None,

145

nonce=None,

146

timestamp=None,

147

): ...

148

149

def sign(

150

self,

151

uri: str,

152

http_method: str = "GET",

153

body: str | dict[str, str] | list[tuple[str, str]] | None = None,

154

headers: dict[str, str] | None = None,

155

realm=None,

156

): ...

157

```

158

159

[OAuth 1.0](./oauth1.md)

160

161

### OAuth 2.0 Clients

162

163

Multiple client implementations supporting all OAuth 2.0 grant types including authorization code, implicit, client credentials, and password flows. Includes PKCE support for enhanced security.

164

165

```python { .api }

166

class WebApplicationClient:

167

def __init__(

168

self,

169

client_id: str,

170

default_token_placement: str = "auth_header",

171

token_type: str = "Bearer",

172

access_token: str | None = None,

173

refresh_token: str | None = None,

174

**kwargs,

175

): ...

176

177

def prepare_authorization_request(

178

self,

179

authorization_url: str,

180

state: str | None = None,

181

redirect_url: str | None = None,

182

scope: str | list[str] | None = None,

183

**kwargs,

184

) -> tuple[str, dict[str, str], str]: ...

185

186

def prepare_token_request(

187

self,

188

token_url: str,

189

authorization_response: str | None = None,

190

redirect_url: str | None = None,

191

state: str | None = None,

192

body: str = "",

193

**kwargs,

194

) -> tuple[str, dict[str, str], str]: ...

195

```

196

197

[OAuth 2.0 Clients](./oauth2-clients.md)

198

199

### OAuth 2.0 Servers

200

201

Complete server-side OAuth 2.0 implementation with authorization servers, resource servers, token endpoints, and request validation. Supports all standard grant types and extensions.

202

203

```python { .api }

204

class WebApplicationServer:

205

def __init__(self, request_validator, token_expires_in=None, token_generator=None, refresh_token_generator=None): ...

206

207

def create_authorization_response(

208

self,

209

uri: str,

210

http_method: str = "GET",

211

body: str | None = None,

212

headers: dict[str, str] | None = None,

213

scopes: list[str] | None = None,

214

credentials: dict[str, str] | None = None,

215

) -> tuple[dict[str, str], str, int]: ...

216

217

def create_token_response(

218

self,

219

uri: str,

220

http_method: str = "POST",

221

body: str | None = None,

222

headers: dict[str, str] | None = None,

223

credentials: dict[str, str] | None = None,

224

**kwargs,

225

) -> tuple[dict[str, str], str, int]: ...

226

```

227

228

[OAuth 2.0 Servers](./oauth2-servers.md)

229

230

### Token Management

231

232

Token creation, validation, and formatting with support for Bearer tokens, MAC tokens, and JWT tokens. Includes token generators, validators, and utility functions for token handling.

233

234

```python { .api }

235

class BearerToken:

236

def __init__(

237

self,

238

request_validator=None,

239

token_generator=None,

240

expires_in: int | None = None,

241

refresh_token_generator=None,

242

): ...

243

244

def create_token(self, request, refresh_token: bool = False, **kwargs) -> dict[str, str]: ...

245

def validate_request(self, request) -> bool: ...

246

247

class OAuth2Token(dict):

248

@property

249

def scope_changed(self) -> bool: ...

250

@property

251

def scopes(self) -> list[str]: ...

252

@property

253

def missing_scopes(self) -> list[str]: ...

254

```

255

256

[Token Management](./token-management.md)

257

258

### Request Validation

259

260

Comprehensive request validation interfaces for both OAuth 1.0 and OAuth 2.0 flows. Provides extensible validation framework for custom authentication logic and security policies.

261

262

```python { .api }

263

class RequestValidator:

264

def validate_client_id(self, client_id: str, request, *args, **kwargs) -> bool: ...

265

def authenticate_client(self, request, *args, **kwargs) -> bool: ...

266

def validate_redirect_uri(self, client_id: str, redirect_uri: str, request, *args, **kwargs) -> bool: ...

267

def validate_scopes(self, client_id: str, scopes: list[str], client, request, *args, **kwargs) -> bool: ...

268

def save_authorization_code(self, client_id: str, code: dict, request, *args, **kwargs) -> None: ...

269

def save_token(self, token: dict, request, *args, **kwargs) -> None: ...

270

```

271

272

[Request Validation](./request-validation.md)

273

274

### Common Utilities

275

276

Shared utilities for parameter handling, token generation, URI validation, and cryptographic operations. Includes request/response handling and OAuth-specific data structures.

277

278

```python { .api }

279

class Request:

280

def __init__(

281

self,

282

uri: str,

283

http_method: str = "GET",

284

body: str | dict[str, str] | list[tuple[str, str]] | None = None,

285

headers: dict[str, str] | None = None,

286

encoding: str = "utf-8",

287

): ...

288

289

@property

290

def uri_query_params(self) -> list[tuple[str, str]]: ...

291

292

def generate_token(length: int = 30, chars: str = ...) -> str: ...

293

def generate_nonce() -> str: ...

294

def generate_timestamp() -> str: ...

295

def safe_string_equals(a: str, b: str) -> bool: ...

296

```

297

298

[Common Utilities](./common-utilities.md)

299

300

### OpenID Connect

301

302

OpenID Connect identity layer implementation providing ID tokens, UserInfo endpoint, and authentication extensions to OAuth 2.0. Includes JWT token handling and claims processing.

303

304

```python { .api }

305

class RequestValidator: # OpenID Connect extension

306

def get_id_token(self, token: dict, token_handler, request) -> str: ...

307

def validate_id_token(self, token: str, scopes: list[str], request) -> bool: ...

308

def get_userinfo_claims(self, request) -> dict | str: ...

309

def validate_silent_authorization(self, request) -> bool: ...

310

311

class Server:

312

def create_userinfo_response(

313

self,

314

uri: str,

315

http_method: str = "GET",

316

body: str | None = None,

317

headers: dict[str, str] | None = None,

318

**kwargs,

319

) -> tuple[dict[str, str], str, int]: ...

320

```

321

322

[OpenID Connect](./openid-connect.md)

323

324

### Device Flow

325

326

OAuth 2.0 device authorization grant (RFC 8628) for input-constrained devices like smart TVs, game consoles, and IoT devices. Provides device and user codes for out-of-band authorization.

327

328

```python { .api }

329

class DeviceClient:

330

def prepare_device_authorization_request(

331

self,

332

device_authorization_endpoint: str,

333

scope: str | list[str] | None = None,

334

**kwargs,

335

) -> tuple[str, dict[str, str], str]: ...

336

337

class DeviceAuthorizationEndpoint:

338

def create_device_authorization_response(

339

self,

340

uri: str,

341

http_method: str = "POST",

342

body: str | None = None,

343

headers: dict[str, str] | None = None,

344

**kwargs,

345

) -> tuple[dict[str, str], str, int]: ...

346

```

347

348

[Device Flow](./device-flow.md)

349

350

### Error Handling

351

352

Comprehensive exception hierarchy for OAuth 1.0, OAuth 2.0, and OpenID Connect errors. Provides specific error types for different failure scenarios with proper HTTP status codes and error responses.

353

354

```python { .api }

355

class OAuth2Error(Exception):

356

error: str | None

357

status_code: int

358

description: str

359

def in_uri(self, uri: str) -> str: ...

360

@property

361

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

362

363

class InvalidClientError(OAuth2Error): ...

364

class InvalidGrantError(OAuth2Error): ...

365

class AccessDeniedError(OAuth2Error): ...

366

class InvalidScopeError(OAuth2Error): ...

367

```

368

369

[Error Handling](./error-handling.md)

370

371

## Types

372

373

```python { .api }

374

# Core module functions

375

def set_debug(debug_val: bool) -> None:

376

"""Set debug mode for the library."""

377

378

def get_debug() -> bool:

379

"""Get current debug mode status."""

380

381

# Module metadata

382

__author__: str

383

__version__: str

384

385

# HTTP method types

386

_HTTPMethod = Literal["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]

387

388

# Token placement options

389

_TokenPlacement = Literal["auth_header", "query", "body"]

390

391

# Case-insensitive dictionary for headers

392

class CaseInsensitiveDict(dict[str, Any]):

393

def __init__(self, data: dict[str, Any]) -> None: ...

394

def __contains__(self, k: str) -> bool: ...

395

def __getitem__(self, k: str): ...

396

def get(self, k: str, default=None): ...

397

398

# OAuth signature method constants

399

SIGNATURE_HMAC_SHA1: str

400

SIGNATURE_RSA_SHA1: str

401

SIGNATURE_PLAINTEXT: str

402

SIGNATURE_TYPE_AUTH_HEADER: str

403

SIGNATURE_TYPE_QUERY: str

404

SIGNATURE_TYPE_BODY: str

405

```