or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

adapters.mdauthentication.mdcookies-exceptions.mddownloads.mdindex.mdmultipart.mdsessions-streaming.mdthreading.mdutilities.md

authentication.mddocs/

0

# Authentication

1

2

Advanced authentication handlers that automatically detect authentication methods and provide specialized authentication support including proxy authentication and compatibility with various authentication schemes.

3

4

## Capabilities

5

6

### Automatic Authentication Detection

7

8

Automatically detects and handles Basic and Digest authentication based on server responses.

9

10

```python { .api }

11

class GuessAuth:

12

"""

13

Authentication handler that guesses the auth type from WWW-Authenticate header.

14

15

Parameters:

16

- username: str, username for authentication

17

- password: str, password for authentication

18

"""

19

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

20

21

# Instance attributes

22

username: str # Username for authentication

23

password: str # Password for authentication

24

auth: Optional[AuthBase] # Determined auth handler (set after detection)

25

pos: Optional[int] # Request body position for rewinding

26

27

def handle_401(self, response, **kwargs):

28

"""

29

Handle 401 Unauthorized responses by detecting auth type.

30

31

Parameters:

32

- response: Response object with 401 status

33

- **kwargs: additional keyword arguments

34

35

Returns:

36

Response: new response with authentication

37

"""

38

39

def __call__(self, request):

40

"""Apply authentication to request."""

41

```

42

43

#### Usage Examples

44

45

```python

46

import requests

47

from requests_toolbelt import GuessAuth

48

49

# Automatic detection of Basic auth

50

response = requests.get(

51

'https://httpbin.org/basic-auth/user/pass',

52

auth=GuessAuth('user', 'pass')

53

)

54

55

# Works with Digest auth too

56

response = requests.get(

57

'https://httpbin.org/digest-auth/auth/user/pass',

58

auth=GuessAuth('user', 'pass')

59

)

60

61

# Use with session for multiple requests

62

session = requests.Session()

63

session.auth = GuessAuth('username', 'password')

64

response = session.get('https://protected-site.com/api/data')

65

```

66

67

### Proxy Authentication

68

69

Handles both server authentication and proxy authentication simultaneously.

70

71

```python { .api }

72

class GuessProxyAuth(GuessAuth):

73

"""

74

Authentication handler for both server and proxy authentication.

75

76

Parameters:

77

- username: str, username for server authentication (optional)

78

- password: str, password for server authentication (optional)

79

- proxy_username: str, username for proxy authentication (optional)

80

- proxy_password: str, password for proxy authentication (optional)

81

"""

82

def __init__(self, username=None, password=None, proxy_username=None, proxy_password=None): ...

83

84

# Instance attributes (inherited + new)

85

username: Optional[str] # Username for server auth

86

password: Optional[str] # Password for server auth

87

proxy_username: Optional[str] # Username for proxy auth

88

proxy_password: Optional[str] # Password for proxy auth

89

auth: Optional[AuthBase] # Determined server auth handler

90

proxy_auth: Optional[AuthBase] # Determined proxy auth handler

91

pos: Optional[int] # Request body position for rewinding

92

93

def handle_401(self, response, **kwargs):

94

"""Handle 401 Unauthorized responses (inherited from GuessAuth)."""

95

96

def handle_407(self, response, **kwargs):

97

"""

98

Handle 407 Proxy Authentication Required responses.

99

100

Parameters:

101

- response: Response object with 407 status

102

- **kwargs: additional keyword arguments

103

104

Returns:

105

Response: new response with proxy authentication

106

"""

107

108

def __call__(self, request):

109

"""Apply authentication to request (overrides GuessAuth)."""

110

```

111

112

#### Usage Examples

113

114

```python

115

import requests

116

from requests_toolbelt.auth.guess import GuessProxyAuth

117

118

# Server authentication only

119

auth = GuessProxyAuth(username='user', password='pass')

120

response = requests.get('https://api.example.com/data', auth=auth)

121

122

# Proxy authentication only

123

auth = GuessProxyAuth(proxy_username='proxy_user', proxy_password='proxy_pass')

124

response = requests.get('https://api.example.com/data', auth=auth)

125

126

# Both server and proxy authentication

127

auth = GuessProxyAuth(

128

username='server_user',

129

password='server_pass',

130

proxy_username='proxy_user',

131

proxy_password='proxy_pass'

132

)

133

response = requests.get('https://api.example.com/data', auth=auth)

134

```

135

136

### Authentication Handler

137

138

General-purpose authentication strategy handler for complex authentication workflows.

139

140

```python { .api }

141

class AuthHandler(AuthBase):

142

"""

143

Generic authentication handler supporting multiple domain-specific strategies.

144

145

Parameters:

146

- strategies: Dict[str, Union[Tuple[str, str], AuthBase]], mapping of domains to auth strategies

147

"""

148

def __init__(self, strategies: Dict[str, Union[Tuple[str, str], AuthBase]]): ...

149

150

# Instance attributes

151

strategies: Dict[str, AuthBase] # Normalized domain -> auth strategy mapping

152

153

def __call__(self, request):

154

"""Apply appropriate authentication strategy based on request URL."""

155

156

def __repr__(self) -> str:

157

"""Return string representation of AuthHandler."""

158

159

def add_strategy(self, domain: str, strategy: Union[Tuple[str, str], AuthBase]) -> None:

160

"""

161

Add a new domain and authentication strategy.

162

163

Parameters:

164

- domain: str, domain URL like 'https://api.github.com'

165

- strategy: Union[Tuple[str, str], AuthBase], auth strategy (tuple converted to HTTPBasicAuth)

166

"""

167

168

def get_strategy_for(self, url: str) -> AuthBase:

169

"""

170

Retrieve the authentication strategy for a specified URL.

171

172

Parameters:

173

- url: str, full URL to get strategy for

174

175

Returns:

176

AuthBase: authentication strategy or NullAuthStrategy if none found

177

"""

178

179

def remove_strategy(self, domain: str) -> None:

180

"""

181

Remove domain and strategy from the collection.

182

183

Parameters:

184

- domain: str, domain to remove

185

"""

186

187

@staticmethod

188

def _key_from_url(url: str) -> str:

189

"""Extract normalized domain key from URL."""

190

191

class NullAuthStrategy(AuthBase):

192

"""No-operation authentication strategy."""

193

194

def __call__(self, request):

195

"""Return request unchanged."""

196

197

def __repr__(self) -> str:

198

"""Return string representation."""

199

```

200

201

#### Usage Examples

202

203

```python

204

import requests

205

from requests_toolbelt.auth.handler import AuthHandler

206

from requests.auth import HTTPBasicAuth, HTTPDigestAuth

207

208

# Create handler with multiple domain strategies

209

auth_handler = AuthHandler({

210

'https://api.github.com': ('github_user', 'github_token'),

211

'https://api.bitbucket.org': HTTPBasicAuth('bb_user', 'bb_pass'),

212

'https://secure-api.com': HTTPDigestAuth('digest_user', 'digest_pass')

213

})

214

215

# Use with requests

216

response = requests.get('https://api.github.com/user', auth=auth_handler)

217

218

# Add new strategy dynamically

219

auth_handler.add_strategy('https://newapi.com', ('new_user', 'new_pass'))

220

221

# Remove strategy

222

auth_handler.remove_strategy('https://api.bitbucket.org')

223

224

# Get strategy for specific URL

225

strategy = auth_handler.get_strategy_for('https://api.github.com/repos')

226

```

227

228

### HTTP Proxy Digest Authentication

229

230

Specialized digest authentication for HTTP proxies.

231

232

```python { .api }

233

class HTTPProxyDigestAuth(HTTPDigestAuth):

234

"""

235

HTTP Proxy Digest Authentication handler with stale rejection tracking.

236

237

Parameters:

238

- *args: Arguments passed to HTTPDigestAuth (username, password)

239

- **kwargs: Keyword arguments passed to HTTPDigestAuth

240

"""

241

def __init__(self, *args, **kwargs): ...

242

243

# Properties

244

@property

245

def stale_rejects(self) -> int:

246

"""

247

Number of stale rejection attempts. Thread-safe property.

248

249

Returns:

250

int: count of stale rejections

251

"""

252

253

@stale_rejects.setter

254

def stale_rejects(self, value: int) -> None:

255

"""Set stale rejection count in thread-safe manner."""

256

257

def init_per_thread_state(self) -> None:

258

"""Initialize per-thread state for digest authentication."""

259

260

def handle_407(self, response, **kwargs):

261

"""

262

Handle 407 Proxy Authentication Required responses.

263

264

Parameters:

265

- response: Response object with 407 status

266

- **kwargs: additional keyword arguments

267

268

Returns:

269

Response: new response with proxy authentication applied

270

271

Raises:

272

IOError: if proxy violates RFC 7235 or credentials are invalid

273

"""

274

275

def __call__(self, request):

276

"""Apply proxy digest authentication to request."""

277

```

278

279

#### Usage Examples

280

281

```python

282

import requests

283

from requests_toolbelt.auth.http_proxy_digest import HTTPProxyDigestAuth

284

285

# Configure proxy with digest authentication

286

proxies = {

287

'http': 'http://proxy.example.com:8080',

288

'https': 'http://proxy.example.com:8080'

289

}

290

291

auth = HTTPProxyDigestAuth('proxy_user', 'proxy_password')

292

293

response = requests.get(

294

'https://api.example.com/data',

295

auth=auth,

296

proxies=proxies

297

)

298

```

299

300

### Digest Authentication Compatibility

301

302

Enhanced digest authentication with compatibility fixes for different versions of requests.

303

304

```python { .api }

305

class HTTPDigestAuth:

306

"""

307

Enhanced HTTP Digest Authentication with compatibility fixes.

308

309

Parameters:

310

- username: str, username for authentication

311

- password: str, password for authentication

312

"""

313

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

314

315

def init_per_thread_state(self):

316

"""Initialize per-thread state for digest auth."""

317

318

def handle_401(self, response, **kwargs):

319

"""Handle 401 Unauthorized responses with digest auth."""

320

321

def __call__(self, request):

322

"""Apply digest authentication to request."""

323

```