0
# Authentication
1
2
Comprehensive authentication support for Trino connections including Basic HTTP authentication, JWT tokens, OAuth2 flows, Kerberos/GSSAPI, and client certificates. All authentication mechanisms integrate seamlessly with both DB-API and low-level client interfaces.
3
4
## Capabilities
5
6
### Authentication Base Class
7
8
Abstract interface for all authentication implementations, providing HTTP session configuration and exception handling.
9
10
```python { .api }
11
class Authentication:
12
def set_http_session(self, http_session: Session) -> Session
13
"""
14
Configure HTTP session with authentication mechanism.
15
16
Parameters:
17
- http_session: requests.Session to configure
18
19
Returns:
20
Configured session instance
21
"""
22
23
def get_exceptions(self) -> Tuple[Any, ...]
24
"""
25
Return tuple of exception types that should trigger retries.
26
27
Returns:
28
Tuple of exception classes
29
"""
30
```
31
32
### Basic Authentication
33
34
HTTP Basic authentication using username and password credentials, suitable for development and testing environments.
35
36
```python { .api }
37
class BasicAuthentication(Authentication):
38
def __init__(self, username: str, password: str)
39
"""
40
Initialize Basic authentication.
41
42
Parameters:
43
- username: Username for authentication
44
- password: Password for authentication
45
"""
46
47
def set_http_session(self, http_session: Session) -> Session
48
"""Configure session with HTTP Basic auth."""
49
50
def get_exceptions(self) -> Tuple[Any, ...]
51
"""Returns empty tuple (no specific exceptions)."""
52
```
53
54
### JWT Authentication
55
56
Bearer token authentication using JSON Web Tokens, commonly used with external identity providers and service accounts.
57
58
```python { .api }
59
class JWTAuthentication(Authentication):
60
def __init__(self, token: str)
61
"""
62
Initialize JWT authentication.
63
64
Parameters:
65
- token: JWT token string
66
"""
67
68
def set_http_session(self, http_session: Session) -> Session
69
"""Configure session with Bearer token authentication."""
70
71
def get_exceptions(self) -> Tuple[Any, ...]
72
"""Returns empty tuple (no specific exceptions)."""
73
```
74
75
### OAuth2 Authentication
76
77
Full OAuth2 flow implementation with configurable redirect handlers and automatic token caching via keyring or in-memory storage.
78
79
```python { .api }
80
class OAuth2Authentication(Authentication):
81
def __init__(
82
self,
83
redirect_auth_url_handler: CompositeRedirectHandler = CompositeRedirectHandler([
84
WebBrowserRedirectHandler(),
85
ConsoleRedirectHandler()
86
])
87
)
88
"""
89
Initialize OAuth2 authentication with redirect handling.
90
91
Parameters:
92
- redirect_auth_url_handler: Handler for OAuth2 redirect URLs
93
"""
94
95
def set_http_session(self, http_session: Session) -> Session
96
"""Configure session with OAuth2 token bearer authentication."""
97
98
def get_exceptions(self) -> Tuple[Any, ...]
99
"""Returns empty tuple (no specific exceptions)."""
100
```
101
102
### OAuth2 Redirect Handlers
103
104
Configurable handlers for OAuth2 authentication redirects supporting browser automation and console output.
105
106
```python { .api }
107
class RedirectHandler:
108
"""Abstract base class for OAuth2 redirect handlers."""
109
def __call__(self, url: str) -> None
110
"""Handle redirect URL."""
111
112
class ConsoleRedirectHandler(RedirectHandler):
113
"""Print OAuth2 URL to console for manual browser navigation."""
114
def __call__(self, url: str) -> None
115
"""Print authentication URL to console."""
116
117
class WebBrowserRedirectHandler(RedirectHandler):
118
"""Automatically open OAuth2 URL in system browser."""
119
def __call__(self, url: str) -> None
120
"""Open URL in default web browser."""
121
122
class CompositeRedirectHandler(RedirectHandler):
123
"""Combine multiple redirect handlers."""
124
def __init__(self, handlers: List[Callable[[str], None]])
125
126
def __call__(self, url: str) -> None
127
"""Execute all configured handlers in sequence."""
128
```
129
130
### Kerberos Authentication
131
132
Kerberos authentication using requests-kerberos library with comprehensive configuration options for enterprise environments.
133
134
```python { .api }
135
class KerberosAuthentication(Authentication):
136
# Class constants for mutual authentication
137
MUTUAL_REQUIRED = 1
138
MUTUAL_OPTIONAL = 2
139
MUTUAL_DISABLED = 3
140
141
def __init__(
142
self,
143
config: Optional[str] = None,
144
service_name: Optional[str] = None,
145
mutual_authentication: int = MUTUAL_REQUIRED,
146
force_preemptive: bool = False,
147
hostname_override: Optional[str] = None,
148
sanitize_mutual_error_response: bool = True,
149
principal: Optional[str] = None,
150
delegate: bool = False,
151
ca_bundle: Optional[str] = None
152
)
153
"""
154
Initialize Kerberos authentication.
155
156
Parameters:
157
- config: Path to Kerberos configuration file
158
- service_name: Service name for authentication
159
- mutual_authentication: Mutual authentication requirement level
160
- force_preemptive: Force preemptive authentication
161
- hostname_override: Override hostname for service principal
162
- sanitize_mutual_error_response: Sanitize error responses
163
- principal: Kerberos principal name
164
- delegate: Enable credential delegation
165
- ca_bundle: Path to CA certificate bundle
166
"""
167
168
def set_http_session(self, http_session: Session) -> Session
169
"""Configure session with Kerberos authentication."""
170
171
def get_exceptions(self) -> Tuple[Any, ...]
172
"""Returns KerberosExchangeError tuple."""
173
```
174
175
### GSSAPI Authentication
176
177
GSSAPI authentication using requests-gssapi library, providing an alternative to Kerberos with potentially better PyPy compatibility.
178
179
```python { .api }
180
class GSSAPIAuthentication(Authentication):
181
# Class constants for mutual authentication
182
MUTUAL_REQUIRED = 1
183
MUTUAL_OPTIONAL = 2
184
MUTUAL_DISABLED = 3
185
186
def __init__(
187
self,
188
config: Optional[str] = None,
189
service_name: Optional[str] = None,
190
mutual_authentication: int = MUTUAL_DISABLED,
191
force_preemptive: bool = False,
192
hostname_override: Optional[str] = None,
193
sanitize_mutual_error_response: bool = True,
194
principal: Optional[str] = None,
195
delegate: bool = False,
196
ca_bundle: Optional[str] = None
197
)
198
"""
199
Initialize GSSAPI authentication.
200
201
Parameters:
202
- config: Path to Kerberos configuration file
203
- service_name: Service name for authentication
204
- mutual_authentication: Mutual authentication requirement level
205
- force_preemptive: Force opportunistic authentication
206
- hostname_override: Override hostname for service principal
207
- sanitize_mutual_error_response: Sanitize error responses
208
- principal: Principal name for credential acquisition
209
- delegate: Enable credential delegation
210
- ca_bundle: Path to CA certificate bundle
211
"""
212
213
def set_http_session(self, http_session: Session) -> Session
214
"""Configure session with GSSAPI authentication."""
215
216
def get_exceptions(self) -> Tuple[Any, ...]
217
"""Returns SPNEGOExchangeError tuple."""
218
```
219
220
### Certificate Authentication
221
222
Client certificate authentication using X.509 certificates for mutual TLS authentication.
223
224
```python { .api }
225
class CertificateAuthentication(Authentication):
226
def __init__(self, cert: str, key: str)
227
"""
228
Initialize certificate authentication.
229
230
Parameters:
231
- cert: Path to client certificate file (PEM format)
232
- key: Path to private key file (PEM format)
233
"""
234
235
def set_http_session(self, http_session: Session) -> Session
236
"""Configure session with client certificate."""
237
238
def get_exceptions(self) -> Tuple[Any, ...]
239
"""Returns empty tuple (no specific exceptions)."""
240
```
241
242
## Usage Examples
243
244
### Basic Authentication
245
246
```python
247
from trino.dbapi import connect
248
from trino.auth import BasicAuthentication
249
250
conn = connect(
251
host="trino.example.com",
252
port=443,
253
user="alice",
254
auth=BasicAuthentication("alice", "secret_password"),
255
http_scheme="https"
256
)
257
```
258
259
### JWT Authentication
260
261
```python
262
from trino.dbapi import connect
263
from trino.auth import JWTAuthentication
264
265
# JWT token from external identity provider
266
jwt_token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
267
268
conn = connect(
269
host="trino.example.com",
270
port=443,
271
user="service-account",
272
auth=JWTAuthentication(jwt_token),
273
http_scheme="https"
274
)
275
```
276
277
### OAuth2 Authentication
278
279
```python
280
from trino.dbapi import connect
281
from trino.auth import OAuth2Authentication, CompositeRedirectHandler, ConsoleRedirectHandler
282
283
# Default behavior: open browser and print to console
284
conn = connect(
285
host="trino.example.com",
286
port=443,
287
user="alice",
288
auth=OAuth2Authentication(),
289
http_scheme="https"
290
)
291
292
# Console-only redirect (for headless environments)
293
console_auth = OAuth2Authentication(
294
redirect_auth_url_handler=CompositeRedirectHandler([ConsoleRedirectHandler()])
295
)
296
297
conn = connect(
298
host="trino.example.com",
299
port=443,
300
user="alice",
301
auth=console_auth,
302
http_scheme="https"
303
)
304
```
305
306
### Kerberos Authentication
307
308
```python
309
from trino.dbapi import connect
310
from trino.auth import KerberosAuthentication
311
312
# Basic Kerberos setup
313
auth = KerberosAuthentication()
314
315
conn = connect(
316
host="trino.example.com",
317
port=443,
318
user="alice@EXAMPLE.COM",
319
auth=auth,
320
http_scheme="https"
321
)
322
323
# Advanced Kerberos configuration
324
auth = KerberosAuthentication(
325
config="/etc/krb5.conf",
326
service_name="HTTP",
327
mutual_authentication=KerberosAuthentication.MUTUAL_REQUIRED,
328
hostname_override="trino.example.com",
329
principal="alice@EXAMPLE.COM",
330
delegate=True
331
)
332
333
conn = connect(
334
host="trino.example.com",
335
port=443,
336
user="alice@EXAMPLE.COM",
337
auth=auth,
338
http_scheme="https"
339
)
340
```
341
342
### GSSAPI Authentication
343
344
```python
345
from trino.dbapi import connect
346
from trino.auth import GSSAPIAuthentication
347
348
# GSSAPI with service name and hostname
349
auth = GSSAPIAuthentication(
350
service_name="HTTP",
351
hostname_override="trino.example.com",
352
principal="alice@EXAMPLE.COM"
353
)
354
355
conn = connect(
356
host="trino.example.com",
357
port=443,
358
user="alice@EXAMPLE.COM",
359
auth=auth,
360
http_scheme="https"
361
)
362
```
363
364
### Certificate Authentication
365
366
```python
367
from trino.dbapi import connect
368
from trino.auth import CertificateAuthentication
369
370
auth = CertificateAuthentication(
371
cert="/path/to/client.crt",
372
key="/path/to/client.key"
373
)
374
375
conn = connect(
376
host="trino.example.com",
377
port=443,
378
user="alice",
379
auth=auth,
380
http_scheme="https"
381
)
382
```
383
384
### SQLAlchemy with Authentication
385
386
```python
387
from sqlalchemy import create_engine
388
from trino.auth import BasicAuthentication
389
390
# Basic auth via connection string
391
engine = create_engine('trino://alice:password@trino.example.com:443/catalog')
392
393
# Authentication via connect_args
394
engine = create_engine(
395
'trino://alice@trino.example.com:443/catalog',
396
connect_args={
397
"auth": BasicAuthentication("alice", "password"),
398
"http_scheme": "https"
399
}
400
)
401
```
402
403
### User Impersonation
404
405
```python
406
from trino.dbapi import connect
407
from trino.auth import BasicAuthentication
408
409
# Connect as service account but execute queries as different user
410
conn = connect(
411
host="trino.example.com",
412
port=443,
413
user="alice", # User for query execution and authorization
414
auth=BasicAuthentication("service", "service_password"), # Authentication credentials
415
http_scheme="https"
416
)
417
```
418
419
### Extra Credentials
420
421
```python
422
from trino.dbapi import connect
423
424
# Pass additional credentials for connectors
425
conn = connect(
426
host="trino.example.com",
427
port=443,
428
user="alice",
429
extra_credential=[
430
("custom.username", "connector_user"),
431
("custom.password", "connector_password")
432
]
433
)
434
```