or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

common-utilities.mddjango-integration.mdflask-integration.mdhttp-clients.mdindex.mdjose.mdoauth1.mdoauth2.mdoidc.md

index.mddocs/

0

# Authlib

1

2

The ultimate Python library in building OAuth and OpenID Connect servers and clients. Authlib provides comprehensive implementations of OAuth 1.0, OAuth 2.0, and OpenID Connect protocols, along with JSON Web Token (JWT) and JSON Object Signing and Encryption (JOSE) standards. It offers spec-compliant implementations covering the entire OAuth ecosystem with built-in support for popular Python web frameworks including Flask, Django, Starlette, and FastAPI.

3

4

## Package Information

5

6

- **Package Name**: Authlib

7

- **Language**: Python

8

- **Installation**: `pip install authlib`

9

- **License**: BSD-3-Clause

10

- **Homepage**: https://authlib.org/

11

- **Documentation**: https://docs.authlib.org/

12

13

## Core Imports

14

15

```python

16

import authlib

17

from authlib import __version__

18

```

19

20

Protocol-specific imports:

21

22

```python

23

# JOSE (JWT, JWS, JWE, JWK)

24

from authlib.jose import JsonWebSignature, JsonWebEncryption, JsonWebKey, JsonWebToken, jwt

25

26

# OAuth 1.0

27

from authlib.oauth1 import OAuth1Request, AuthorizationServer, ResourceProtector, OAuth1Client

28

29

# OAuth 2.0

30

from authlib.oauth2 import OAuth2Client, AuthorizationServer, ResourceProtector, OAuth2Request

31

32

# OpenID Connect

33

from authlib.oidc.core import IDToken, UserInfo, UserInfoEndpoint

34

```

35

36

Framework integrations:

37

38

```python

39

# Flask

40

from authlib.integrations.flask_client import OAuth

41

from authlib.integrations.flask_oauth2 import AuthorizationServer

42

43

# Django

44

from authlib.integrations.django_oauth2 import AuthorizationServer

45

46

# Requests/HTTPX

47

from authlib.integrations.requests_client import OAuth1Session, OAuth2Session

48

from authlib.integrations.httpx_client import OAuth1Client, OAuth2Client

49

```

50

51

## Basic Usage

52

53

### JWT Operations

54

55

```python

56

from authlib.jose import JsonWebToken, jwt

57

58

# Create a JWT token

59

header = {'alg': 'HS256'}

60

payload = {'user_id': 123, 'username': 'alice'}

61

secret = 'your-secret-key'

62

63

token = jwt.encode(header, payload, secret)

64

print(token) # JWT token string

65

66

# Decode and validate JWT token

67

data = jwt.decode(token, secret)

68

print(data) # {'user_id': 123, 'username': 'alice'}

69

```

70

71

### OAuth 2.0 Client

72

73

```python

74

from authlib.integrations.requests_client import OAuth2Session

75

76

# Create OAuth 2.0 client

77

client = OAuth2Session(

78

client_id='your-client-id',

79

client_secret='your-client-secret',

80

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

81

)

82

83

# Authorization URL

84

authorization_url, state = client.create_authorization_url(

85

'https://provider.com/authorize',

86

scope='read write'

87

)

88

89

# Exchange authorization code for token

90

token = client.fetch_token(

91

'https://provider.com/token',

92

authorization_response='https://your-app.com/callback?code=...'

93

)

94

95

# Make authenticated requests

96

response = client.get('https://api.provider.com/user')

97

```

98

99

### OpenID Connect

100

101

```python

102

from authlib.oidc.core import IDToken

103

from authlib.jose import JsonWebToken

104

105

# Validate ID Token

106

id_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...'

107

jwt = JsonWebToken(['RS256'])

108

109

# Claims validation

110

claims = jwt.decode(id_token, public_key)

111

id_token_claims = IDToken(claims)

112

id_token_claims.validate()

113

```

114

115

## Architecture

116

117

Authlib is organized into several key modules:

118

119

- **jose**: JSON Object Signing and Encryption (JOSE) implementations including JWT, JWS, JWE, and JWK

120

- **oauth1**: OAuth 1.0 protocol implementation for both clients and servers

121

- **oauth2**: OAuth 2.0 protocol implementation with support for all standard grant types

122

- **oidc**: OpenID Connect layer built on top of OAuth 2.0

123

- **integrations**: Framework-specific implementations for Flask, Django, Starlette, Requests, and HTTPX

124

- **common**: Shared utilities for encoding, security, URL handling, and error management

125

126

The library provides both high-level framework integrations and low-level protocol implementations, allowing developers to choose the appropriate abstraction level for their needs.

127

128

## Capabilities

129

130

### JOSE (JSON Object Signing and Encryption)

131

132

Complete implementation of JOSE standards including JWT (JSON Web Tokens), JWS (JSON Web Signature), JWE (JSON Web Encryption), and JWK (JSON Web Keys). Supports all standard algorithms and provides both high-level JWT operations and low-level JOSE primitives.

133

134

```python { .api }

135

class JsonWebToken:

136

def encode(self, header: dict, payload: dict, key: str) -> str: ...

137

def decode(self, data: str, key: str) -> dict: ...

138

139

class JsonWebSignature:

140

def serialize_compact(self, protected: dict, payload: bytes, key: str) -> str: ...

141

def deserialize_compact(self, data: str, key: str) -> dict: ...

142

143

class JsonWebKey:

144

def import_key(self, key: str) -> Key: ...

145

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

146

```

147

148

[JOSE Implementation](./jose.md)

149

150

### OAuth 1.0 Protocol

151

152

Full OAuth 1.0 implementation supporting all signature methods (HMAC-SHA1, RSA-SHA1, PLAINTEXT) and signature types (header, query, body). Provides both client and server implementations with support for temporary credentials and token credentials.

153

154

```python { .api }

155

class OAuth1Client:

156

def __init__(self, client_key: str, client_secret: str = None) -> None: ...

157

def fetch_request_token(self, uri: str, realm: str = None) -> dict: ...

158

def fetch_access_token(self, uri: str, verifier: str = None) -> dict: ...

159

160

class AuthorizationServer:

161

def __init__(self, query_client: callable, query_token: callable) -> None: ...

162

def validate_request(self, uri: str, http_method: str, body: str, headers: dict) -> None: ...

163

```

164

165

[OAuth 1.0 Implementation](./oauth1.md)

166

167

### OAuth 2.0 Protocol

168

169

Comprehensive OAuth 2.0 implementation supporting all standard grant types: authorization code, implicit, resource owner password credentials, client credentials, and refresh token. Includes support for PKCE, device flow, and bearer tokens.

170

171

```python { .api }

172

class OAuth2Client:

173

def __init__(self, client_id: str, client_secret: str = None) -> None: ...

174

def create_authorization_url(self, authorization_endpoint: str, **kwargs) -> tuple: ...

175

def fetch_token(self, token_endpoint: str, **kwargs) -> dict: ...

176

177

class AuthorizationServer:

178

def __init__(self, query_client: callable, save_token: callable) -> None: ...

179

def validate_consent_request(self, request: OAuth2Request) -> None: ...

180

def create_authorization_response(self, request: OAuth2Request, grant_user: callable) -> HttpResponse: ...

181

```

182

183

[OAuth 2.0 Implementation](./oauth2.md)

184

185

### OpenID Connect

186

187

OpenID Connect implementation built on OAuth 2.0, providing ID tokens, UserInfo endpoint, and discovery mechanisms. Supports all OpenID Connect flows: authorization code, implicit, and hybrid.

188

189

```python { .api }

190

class IDToken:

191

def __init__(self, claims: dict) -> None: ...

192

def validate(self, now: int = None) -> None: ...

193

194

class UserInfo:

195

def __init__(self, sub: str, **claims) -> None: ...

196

def __call__(self, claims: list = None) -> dict: ...

197

198

class UserInfoEndpoint:

199

def create_userinfo_response(self, request: OAuth2Request) -> HttpResponse: ...

200

```

201

202

[OpenID Connect Implementation](./oidc.md)

203

204

### Flask Integration

205

206

Complete Flask integration providing OAuth client registry and OAuth 2.0 server implementations. Supports automatic token management, session integration, and Flask-specific request/response handling.

207

208

```python { .api }

209

class OAuth:

210

def __init__(self, app: Flask = None) -> None: ...

211

def register(self, name: str, **kwargs) -> FlaskOAuth2App: ...

212

213

class AuthorizationServer:

214

def __init__(self, app: Flask = None) -> None: ...

215

def init_app(self, app: Flask, query_client: callable, save_token: callable) -> None: ...

216

```

217

218

[Flask Integration](./flask-integration.md)

219

220

### Django Integration

221

222

Django-specific OAuth 2.0 server implementation with Django model integration, middleware support, and Django-specific request/response handling.

223

224

```python { .api }

225

class AuthorizationServer:

226

def __init__(self, query_client: callable, save_token: callable) -> None: ...

227

def create_token_response(self, request: HttpRequest) -> HttpResponse: ...

228

229

class ResourceProtector:

230

def __init__(self, require_oauth: callable = None) -> None: ...

231

def acquire_token(self, request: HttpRequest, scope: str = None) -> OAuth2Token: ...

232

```

233

234

[Django Integration](./django-integration.md)

235

236

### HTTP Client Integrations

237

238

Seamless integration with popular HTTP clients including Requests and HTTPX for both synchronous and asynchronous OAuth operations. Provides automatic token management and request signing.

239

240

```python { .api }

241

# Requests integration

242

class OAuth1Session:

243

def __init__(self, client_key: str, client_secret: str = None) -> None: ...

244

245

class OAuth2Session:

246

def __init__(self, client_id: str, client_secret: str = None) -> None: ...

247

248

# HTTPX integration

249

class OAuth1Client:

250

def __init__(self, client_key: str, client_secret: str = None) -> None: ...

251

252

class OAuth2Client:

253

def __init__(self, client_id: str, client_secret: str = None) -> None: ...

254

```

255

256

[HTTP Client Integrations](./http-clients.md)

257

258

### Common Utilities

259

260

Shared utilities for encoding, security operations, URL handling, and error management used throughout the library. Provides consistent behavior and security best practices.

261

262

```python { .api }

263

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

264

def is_secure_transport(uri: str) -> bool: ...

265

def url_encode(params: dict) -> str: ...

266

def url_decode(query: str) -> dict: ...

267

```

268

269

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

270

271

## Error Handling

272

273

Authlib provides comprehensive error handling with specific exception classes for different protocols and scenarios:

274

275

```python { .api }

276

class AuthlibBaseError(Exception): ...

277

class OAuth2Error(AuthlibBaseError): ...

278

class JoseError(AuthlibBaseError): ...

279

class InvalidTokenError(OAuth2Error): ...

280

class ExpiredTokenError(JoseError): ...

281

```

282

283

All errors include detailed messages and, where applicable, HTTP status codes for proper error responses in server implementations.