or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdconfiguration.mdexceptions.mdindex.mdpaging.mdpipeline.mdpolling.mdserialization.mdservice-client.md

authentication.mddocs/

0

# Authentication

1

2

Comprehensive authentication system supporting multiple authentication schemes including Basic, Bearer token, OAuth2, API keys, Kerberos, and Azure service-specific credentials. The authentication system is designed to be pluggable and extensible for various REST API requirements.

3

4

## Capabilities

5

6

### Base Authentication

7

8

Base authentication class providing the foundation for all authentication mechanisms.

9

10

```python { .api }

11

class Authentication:

12

header: str = "Authorization"

13

14

def signed_session(self, session=None):

15

"""

16

Create requests session with auth headers applied.

17

18

Parameters:

19

- session: Optional existing requests.Session to configure

20

21

Returns:

22

Configured requests.Session object

23

"""

24

```

25

26

### Basic Authentication

27

28

HTTP Basic authentication using username and password credentials.

29

30

```python { .api }

31

class BasicAuthentication(Authentication):

32

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

33

"""

34

Initialize Basic authentication.

35

36

Parameters:

37

- username: Authentication username

38

- password: Authentication password

39

"""

40

41

scheme: str = 'Basic'

42

username: str

43

password: str

44

```

45

46

### Token Authentication

47

48

Simple Bearer token authentication for APIs that use static tokens.

49

50

```python { .api }

51

class BasicTokenAuthentication(Authentication):

52

def __init__(self, token: dict):

53

"""

54

Initialize Bearer token authentication.

55

56

Parameters:

57

- token: Token dict with 'access_token' key

58

"""

59

60

scheme: str = 'Bearer'

61

token: dict

62

63

def set_token(self):

64

"""Define token attribute (no-op in basic implementation)."""

65

```

66

67

### OAuth2 Authentication

68

69

OAuth2 token authentication with automatic token refresh capabilities.

70

71

```python { .api }

72

class OAuthTokenAuthentication(BasicTokenAuthentication):

73

def __init__(self, client_id: str, token: dict):

74

"""

75

Initialize OAuth2 authentication.

76

77

Parameters:

78

- client_id: OAuth2 client ID

79

- token: OAuth2 token dict with expires_in field required

80

"""

81

82

id: str # OAuth2 client ID

83

store_key: str # Storage key for token

84

85

def construct_auth(self) -> str:

86

"""

87

Format token header string.

88

89

Note: Uses requests_oauthlib.OAuth2 instead of manual header construction

90

"""

91

92

def refresh_session(self, session=None):

93

"""

94

Return updated session with OAuth2 authentication configured.

95

96

Parameters:

97

- session: Optional existing session to update

98

99

Returns:

100

Updated requests.Session with OAuth2 auth

101

102

Note: Does not call parent signed_session by design

103

"""

104

```

105

106

### Kerberos Authentication

107

108

Kerberos Single Sign-On (SSO) authentication requiring requests_kerberos package.

109

110

```python { .api }

111

class KerberosAuthentication(Authentication):

112

def __init__(self, mutual_authentication=None):

113

"""

114

Initialize Kerberos authentication.

115

116

Parameters:

117

- mutual_authentication: Mutual auth requirement (REQUIRED, OPTIONAL, DISABLED)

118

119

Raises:

120

- ImportError: If requests_kerberos package is not installed

121

"""

122

123

mutual_authentication: any # Kerberos mutual authentication setting

124

```

125

126

### API Key Credentials

127

128

API key authentication supporting keys in headers and/or query parameters.

129

130

```python { .api }

131

class ApiKeyCredentials(Authentication):

132

def __init__(self, in_headers=None, in_query=None):

133

"""

134

Initialize API key authentication.

135

136

Parameters:

137

- in_headers: Dict of header-based API keys

138

- in_query: Dict of query parameter-based API keys

139

140

Raises:

141

- ValueError: If both in_headers and in_query are None or empty

142

- ValueError: If session.params is not a dict during signing

143

"""

144

145

in_headers: dict # API keys to include in request headers

146

in_query: dict # API keys to include in query parameters

147

```

148

149

### Azure Service Credentials

150

151

Specialized credential classes for Azure services with predefined header formats.

152

153

```python { .api }

154

class CognitiveServicesCredentials(ApiKeyCredentials):

155

_subscription_key_header = 'Ocp-Apim-Subscription-Key'

156

157

def __init__(self, subscription_key: str):

158

"""

159

Cognitive Services authentication.

160

161

Parameters:

162

- subscription_key: Azure Cognitive Services subscription key

163

164

Raises:

165

- ValueError: If subscription_key is None

166

167

Note: Automatically adds X-BingApis-SDK-Client header

168

"""

169

170

class TopicCredentials(ApiKeyCredentials):

171

_topic_key_header = 'aeg-sas-key'

172

173

def __init__(self, topic_key: str):

174

"""

175

Event Grid topic authentication.

176

177

Parameters:

178

- topic_key: Event Grid topic access key

179

180

Raises:

181

- ValueError: If topic_key is None

182

"""

183

184

class DomainCredentials(ApiKeyCredentials):

185

_domain_key_header = 'aeg-sas-key'

186

187

def __init__(self, domain_key: str):

188

"""

189

Event Grid domain authentication.

190

191

Parameters:

192

- domain_key: Event Grid domain access key

193

194

Raises:

195

- ValueError: If domain_key is None

196

"""

197

```

198

199

## Usage Examples

200

201

### Basic Authentication

202

203

```python

204

from msrest import ServiceClient, Configuration

205

from msrest.authentication import BasicAuthentication

206

207

# Create basic auth

208

auth = BasicAuthentication('myusername', 'mypassword')

209

210

# Configure client

211

config = Configuration(base_url='https://api.example.com')

212

config.credentials = auth

213

214

# Use client

215

with ServiceClient(None, config) as client:

216

request = client.get('/protected/resource')

217

response = client.send(request)

218

```

219

220

### API Key Authentication

221

222

```python

223

from msrest.authentication import ApiKeyCredentials

224

225

# API key in header

226

auth = ApiKeyCredentials(in_headers={'X-API-Key': 'your-api-key-here'})

227

228

# API key in query parameter

229

auth = ApiKeyCredentials(in_query={'api_key': 'your-api-key-here'})

230

231

# API key in both header and query

232

auth = ApiKeyCredentials(

233

in_headers={'Authorization': 'Bearer your-token'},

234

in_query={'client_id': 'your-client-id'}

235

)

236

```

237

238

### OAuth2 Token Authentication

239

240

```python

241

from msrest.authentication import OAuthTokenAuthentication

242

243

# OAuth2 token (assuming you've obtained it through OAuth flow)

244

token = {

245

'access_token': 'your-access-token',

246

'token_type': 'Bearer',

247

'expires_in': 3600,

248

'refresh_token': 'your-refresh-token'

249

}

250

251

auth = OAuthTokenAuthentication('your-client-id', token)

252

253

# The authentication will automatically handle token refresh

254

config = Configuration(base_url='https://api.example.com')

255

config.credentials = auth

256

```

257

258

### Azure Cognitive Services

259

260

```python

261

from msrest.authentication import CognitiveServicesCredentials

262

263

# Use Azure Cognitive Services subscription key

264

auth = CognitiveServicesCredentials('your-subscription-key')

265

266

config = Configuration(base_url='https://westus.api.cognitive.microsoft.com')

267

config.credentials = auth

268

```

269

270

### Kerberos Authentication

271

272

```python

273

from msrest.authentication import KerberosAuthentication

274

275

# Requires: pip install requests_kerberos

276

try:

277

from requests_kerberos import REQUIRED, OPTIONAL, DISABLED

278

279

# Use Kerberos with required mutual authentication

280

auth = KerberosAuthentication(mutual_authentication=REQUIRED)

281

282

config = Configuration(base_url='https://api.example.com')

283

config.credentials = auth

284

285

except ImportError:

286

print("Install requests_kerberos for Kerberos support")

287

```

288

289

### Custom Session Configuration

290

291

```python

292

import requests

293

from msrest.authentication import BasicAuthentication

294

295

# Create authentication

296

auth = BasicAuthentication('username', 'password')

297

298

# Get configured session

299

session = auth.signed_session()

300

301

# Customize session further

302

session.verify = False # Disable SSL verification

303

session.proxies = {'http': 'http://proxy.example.com:8080'}

304

305

# Use session directly or with ServiceClient

306

response = session.get('https://api.example.com/data')

307

```

308

309

## Integration with Service Client

310

311

Authentication credentials can be set on the Configuration object:

312

313

```python

314

from msrest import ServiceClient, Configuration

315

from msrest.authentication import ApiKeyCredentials

316

317

# Method 1: Set credentials on config

318

config = Configuration(base_url='https://api.example.com')

319

config.credentials = ApiKeyCredentials(in_headers={'X-API-Key': 'key'})

320

321

client = ServiceClient(None, config)

322

323

# Method 2: Pass credentials to client (deprecated)

324

auth = ApiKeyCredentials(in_headers={'X-API-Key': 'key'})

325

client = ServiceClient(auth, config)

326

```

327

328

## Error Handling

329

330

Authentication errors are handled through specific exception types:

331

332

```python

333

from msrest.exceptions import AuthenticationError, TokenExpiredError

334

335

try:

336

with ServiceClient(None, config) as client:

337

response = client.send(request)

338

except AuthenticationError as e:

339

print(f"Authentication failed: {e}")

340

except TokenExpiredError as e:

341

print(f"Token expired: {e}")

342

# Handle token refresh

343

```