0
# Authentication and Security
1
2
Comprehensive authentication support for all MySQL authentication methods including enterprise security features, SSL/TLS encryption, and advanced authentication plugins.
3
4
## Authentication Overview
5
6
MySQL Connector/Python supports all MySQL authentication plugins through a flexible plugin system that handles various authentication methods from basic password authentication to enterprise features like Kerberos, LDAP, and WebAuthn.
7
8
## Core Authentication Classes
9
10
### MySQLAuthenticationPlugin
11
12
```python { .api }
13
class MySQLAuthenticationPlugin:
14
"""
15
Base class for MySQL authentication plugins.
16
Provides interface for implementing authentication methods.
17
"""
18
19
plugin_name: str = None # Plugin name identifier
20
requires_ssl: bool = False # Whether plugin requires SSL connection
21
22
def prepare_password(self, password: str) -> bytes:
23
"""
24
Prepare password for authentication.
25
26
Args:
27
password: Plain text password
28
29
Returns:
30
Prepared password bytes
31
"""
32
pass
33
34
def auth_response(self, auth_data: bytes, **kwargs) -> bytes:
35
"""
36
Generate authentication response.
37
38
Args:
39
auth_data: Server authentication challenge data
40
**kwargs: Additional authentication parameters
41
42
Returns:
43
Authentication response bytes
44
"""
45
pass
46
```
47
48
## Standard Authentication Plugins
49
50
### mysql_native_password
51
52
```python { .api }
53
class mysql_native_password:
54
"""
55
MySQL native password authentication plugin.
56
Uses SHA1-based hashing for password authentication.
57
"""
58
59
plugin_name: str = 'mysql_native_password'
60
requires_ssl: bool = False
61
62
@staticmethod
63
def prepare_password(password: str) -> bytes:
64
"""Prepare password using SHA1 hashing algorithm."""
65
pass
66
67
def auth_response(self, auth_data: bytes, password: str = '', **kwargs) -> bytes:
68
"""Generate native password authentication response."""
69
pass
70
```
71
72
### caching_sha2_password
73
74
```python { .api }
75
class caching_sha2_password:
76
"""
77
Caching SHA2 password authentication plugin.
78
Default authentication method for MySQL 8.0+.
79
Uses SHA256-based hashing with server-side caching.
80
"""
81
82
plugin_name: str = 'caching_sha2_password'
83
requires_ssl: bool = False # SSL recommended but not required
84
85
@staticmethod
86
def prepare_password(password: str) -> bytes:
87
"""Prepare password using SHA256 hashing algorithm."""
88
pass
89
90
def auth_response(self, auth_data: bytes, password: str = '', ssl_enabled: bool = False, **kwargs) -> bytes:
91
"""Generate caching SHA2 authentication response."""
92
pass
93
```
94
95
### sha256_password
96
97
```python { .api }
98
class sha256_password:
99
"""
100
SHA256 password authentication plugin.
101
Uses RSA encryption over SSL or plain connection with public key.
102
"""
103
104
plugin_name: str = 'sha256_password'
105
requires_ssl: bool = True # Requires SSL for secure password transmission
106
107
@staticmethod
108
def prepare_password(password: str) -> bytes:
109
"""Prepare password for SHA256 authentication."""
110
pass
111
112
def auth_response(self, auth_data: bytes, password: str = '', ssl_enabled: bool = False, **kwargs) -> bytes:
113
"""Generate SHA256 authentication response."""
114
pass
115
```
116
117
### mysql_clear_password
118
119
```python { .api }
120
class mysql_clear_password:
121
"""
122
Clear text password authentication plugin.
123
Sends password in plain text - requires SSL for security.
124
"""
125
126
plugin_name: str = 'mysql_clear_password'
127
requires_ssl: bool = True # SSL required for security
128
129
def auth_response(self, auth_data: bytes, password: str = '', **kwargs) -> bytes:
130
"""Send clear text password (requires SSL)."""
131
pass
132
```
133
134
## Enterprise Authentication Plugins
135
136
### authentication_kerberos_client
137
138
```python { .api }
139
class authentication_kerberos_client:
140
"""
141
Kerberos authentication plugin for MySQL Enterprise.
142
Integrates with Active Directory and Kerberos infrastructure.
143
"""
144
145
plugin_name: str = 'authentication_kerberos_client'
146
requires_ssl: bool = False
147
148
def __init__(self, **kwargs) -> None:
149
"""Initialize Kerberos authentication with configuration."""
150
pass
151
152
def auth_response(self, auth_data: bytes, **kwargs) -> bytes:
153
"""Perform Kerberos authentication handshake."""
154
pass
155
```
156
157
### authentication_ldap_sasl_client
158
159
```python { .api }
160
class authentication_ldap_sasl_client:
161
"""
162
LDAP SASL authentication plugin for MySQL Enterprise.
163
Supports LDAP authentication with SASL mechanisms.
164
"""
165
166
plugin_name: str = 'authentication_ldap_sasl_client'
167
requires_ssl: bool = True
168
169
def __init__(self, **kwargs) -> None:
170
"""Initialize LDAP SASL authentication."""
171
pass
172
173
def auth_response(self, auth_data: bytes, password: str = '', **kwargs) -> bytes:
174
"""Perform LDAP SASL authentication."""
175
pass
176
```
177
178
### authentication_oci_client
179
180
```python { .api }
181
class authentication_oci_client:
182
"""
183
Oracle Cloud Infrastructure (OCI) authentication plugin.
184
Uses OCI Identity and Access Management for authentication.
185
"""
186
187
plugin_name: str = 'authentication_oci_client'
188
requires_ssl: bool = True
189
190
def __init__(self, **kwargs) -> None:
191
"""Initialize OCI authentication with configuration."""
192
pass
193
194
def auth_response(self, auth_data: bytes, **kwargs) -> bytes:
195
"""Perform OCI authentication using IAM tokens."""
196
pass
197
```
198
199
### authentication_webauthn_client
200
201
```python { .api }
202
class authentication_webauthn_client:
203
"""
204
WebAuthn authentication plugin for MySQL Enterprise.
205
Supports FIDO2/WebAuthn multi-factor authentication.
206
"""
207
208
plugin_name: str = 'authentication_webauthn_client'
209
requires_ssl: bool = True
210
211
def __init__(self, **kwargs) -> None:
212
"""Initialize WebAuthn authentication."""
213
pass
214
215
def auth_response(self, auth_data: bytes, **kwargs) -> bytes:
216
"""Perform WebAuthn authentication challenge."""
217
pass
218
```
219
220
### authentication_openid_connect_client
221
222
```python { .api }
223
class authentication_openid_connect_client:
224
"""
225
OpenID Connect authentication plugin for MySQL Enterprise.
226
Supports OAuth 2.0/OpenID Connect authentication flows.
227
"""
228
229
plugin_name: str = 'authentication_openid_connect_client'
230
requires_ssl: bool = True
231
232
def __init__(self, **kwargs) -> None:
233
"""Initialize OpenID Connect authentication."""
234
pass
235
236
def auth_response(self, auth_data: bytes, **kwargs) -> bytes:
237
"""Perform OpenID Connect authentication flow."""
238
pass
239
```
240
241
## SSL/TLS Security Configuration
242
243
### SSL Connection Parameters
244
245
```python { .api }
246
ssl_config = {
247
'ssl_disabled': bool, # Disable SSL/TLS (default: False)
248
'ssl_cert': str, # Client certificate file path
249
'ssl_key': str, # Client private key file path
250
'ssl_ca': str, # Certificate authority file path
251
'ssl_capath': str, # Certificate authority directory path
252
'ssl_cipher': str, # SSL cipher specification
253
'ssl_verify_cert': bool, # Verify server certificate (default: False)
254
'ssl_verify_identity': bool, # Verify server identity (default: False)
255
'tls_versions': List[str], # Allowed TLS versions (['TLSv1.2', 'TLSv1.3'])
256
'tls_ciphersuites': List[str], # Allowed TLS 1.3 cipher suites
257
}
258
```
259
260
### SSL Certificate Verification Modes
261
262
```python { .api }
263
# SSL verification levels
264
SSL_MODES = {
265
'DISABLED': {
266
'ssl_disabled': True
267
},
268
'PREFERRED': {
269
'ssl_disabled': False,
270
'ssl_verify_cert': False,
271
'ssl_verify_identity': False
272
},
273
'REQUIRED': {
274
'ssl_disabled': False,
275
'ssl_verify_cert': False,
276
'ssl_verify_identity': False
277
},
278
'VERIFY_CA': {
279
'ssl_disabled': False,
280
'ssl_verify_cert': True,
281
'ssl_verify_identity': False
282
},
283
'VERIFY_IDENTITY': {
284
'ssl_disabled': False,
285
'ssl_verify_cert': True,
286
'ssl_verify_identity': True
287
}
288
}
289
```
290
291
## Multi-Factor Authentication
292
293
### MFA Configuration
294
295
```python { .api }
296
mfa_config = {
297
'password1': str, # First factor password
298
'password2': str, # Second factor password (MFA)
299
'password3': str, # Third factor password (MFA)
300
'auth_plugin': str, # Primary authentication plugin
301
'auth_plugin_map': Dict[str, Type], # Plugin mapping for different factors
302
}
303
```
304
305
## Authentication Configuration Examples
306
307
### Basic Password Authentication
308
309
```python
310
import mysql.connector
311
312
# Native password authentication (MySQL 5.7 and earlier default)
313
connection = mysql.connector.connect(
314
host='localhost',
315
user='myuser',
316
password='mypassword',
317
database='mydatabase',
318
auth_plugin='mysql_native_password'
319
)
320
321
cursor = connection.cursor()
322
cursor.execute("SELECT USER(), @@authentication_windows_use_principal_name")
323
result = cursor.fetchone()
324
print(f"Connected as: {result[0]}")
325
326
cursor.close()
327
connection.close()
328
```
329
330
### SHA2 Caching Authentication
331
332
```python
333
import mysql.connector
334
335
# Caching SHA2 password authentication (MySQL 8.0+ default)
336
connection = mysql.connector.connect(
337
host='localhost',
338
user='myuser',
339
password='mypassword',
340
database='mydatabase',
341
auth_plugin='caching_sha2_password'
342
)
343
344
print("Connected using caching_sha2_password")
345
connection.close()
346
```
347
348
### SSL/TLS with Certificate Authentication
349
350
```python
351
import mysql.connector
352
353
# SSL configuration with client certificates
354
ssl_config = {
355
'ssl_cert': '/path/to/client-cert.pem',
356
'ssl_key': '/path/to/client-key.pem',
357
'ssl_ca': '/path/to/ca-cert.pem',
358
'ssl_verify_cert': True,
359
'ssl_verify_identity': True,
360
'tls_versions': ['TLSv1.2', 'TLSv1.3']
361
}
362
363
connection = mysql.connector.connect(
364
host='mysql.example.com',
365
user='myuser',
366
password='mypassword',
367
database='mydatabase',
368
**ssl_config
369
)
370
371
print("Secure SSL connection established with certificate verification")
372
connection.close()
373
```
374
375
### Multi-Factor Authentication
376
377
```python
378
import mysql.connector
379
380
# Multi-factor authentication setup
381
mfa_config = {
382
'host': 'localhost',
383
'user': 'mfa_user',
384
'password1': 'first_factor_password', # Primary password
385
'password2': 'second_factor_password', # Second factor (e.g., SMS/TOTP)
386
'password3': 'third_factor_password', # Third factor (e.g., hardware token)
387
'database': 'mydatabase',
388
'auth_plugin': 'caching_sha2_password'
389
}
390
391
try:
392
connection = mysql.connector.connect(**mfa_config)
393
print("Multi-factor authentication successful")
394
connection.close()
395
except mysql.connector.Error as err:
396
print(f"MFA authentication failed: {err}")
397
```
398
399
### Kerberos Authentication
400
401
```python
402
import mysql.connector
403
404
# Kerberos authentication configuration
405
kerberos_config = {
406
'host': 'mysql.corporate.com',
407
'user': 'kerberos_user@CORPORATE.COM',
408
'database': 'mydatabase',
409
'auth_plugin': 'authentication_kerberos_client',
410
'authentication_kerberos_client_mode': 1, # GSSAPI mode
411
'ssl_disabled': False, # SSL recommended with Kerberos
412
'ssl_verify_cert': True
413
}
414
415
try:
416
connection = mysql.connector.connect(**kerberos_config)
417
print("Kerberos authentication successful")
418
419
cursor = connection.cursor()
420
cursor.execute("SELECT USER()")
421
result = cursor.fetchone()
422
print(f"Authenticated as: {result[0]}")
423
424
cursor.close()
425
connection.close()
426
427
except mysql.connector.Error as err:
428
print(f"Kerberos authentication failed: {err}")
429
```
430
431
### LDAP SASL Authentication
432
433
```python
434
import mysql.connector
435
436
# LDAP SASL authentication configuration
437
ldap_config = {
438
'host': 'mysql.corporate.com',
439
'user': 'ldap_user',
440
'password': 'ldap_password',
441
'database': 'mydatabase',
442
'auth_plugin': 'authentication_ldap_sasl_client',
443
'authentication_ldap_sasl_client_mode': 1, # SCRAM-SHA-1 mode
444
'ssl_disabled': False, # SSL required for LDAP SASL
445
'ssl_verify_cert': True
446
}
447
448
try:
449
connection = mysql.connector.connect(**ldap_config)
450
print("LDAP SASL authentication successful")
451
connection.close()
452
except mysql.connector.Error as err:
453
print(f"LDAP authentication failed: {err}")
454
```
455
456
### OCI (Oracle Cloud) Authentication
457
458
```python
459
import mysql.connector
460
461
# OCI authentication configuration
462
oci_config = {
463
'host': 'mysql.oraclecloud.com',
464
'user': 'oci_user',
465
'database': 'mydatabase',
466
'auth_plugin': 'authentication_oci_client',
467
'oci_config_file': '~/.oci/config', # OCI config file
468
'oci_config_profile': 'DEFAULT', # OCI profile name
469
'ssl_disabled': False,
470
'ssl_verify_cert': True
471
}
472
473
try:
474
connection = mysql.connector.connect(**oci_config)
475
print("OCI authentication successful")
476
connection.close()
477
except mysql.connector.Error as err:
478
print(f"OCI authentication failed: {err}")
479
```
480
481
### WebAuthn Authentication
482
483
```python
484
import mysql.connector
485
486
# WebAuthn authentication configuration
487
webauthn_config = {
488
'host': 'mysql.enterprise.com',
489
'user': 'webauthn_user',
490
'database': 'mydatabase',
491
'auth_plugin': 'authentication_webauthn_client',
492
'authentication_webauthn_client_mode': 1, # Platform authenticator mode
493
'ssl_disabled': False, # SSL required for WebAuthn
494
'ssl_verify_cert': True
495
}
496
497
try:
498
# Note: WebAuthn would typically require user interaction with hardware token
499
connection = mysql.connector.connect(**webauthn_config)
500
print("WebAuthn authentication successful")
501
connection.close()
502
except mysql.connector.Error as err:
503
print(f"WebAuthn authentication failed: {err}")
504
```
505
506
### Custom Authentication Plugin
507
508
```python
509
import mysql.connector
510
from mysql.connector.authentication import MySQLAuthenticationPlugin
511
512
class CustomAuthPlugin(MySQLAuthenticationPlugin):
513
"""Custom authentication plugin implementation."""
514
515
plugin_name = 'custom_auth_plugin'
516
requires_ssl = True
517
518
def prepare_password(self, password: str) -> bytes:
519
"""Custom password preparation logic."""
520
# Implement custom password hashing/preparation
521
return password.encode('utf-8')
522
523
def auth_response(self, auth_data: bytes, password: str = '', **kwargs) -> bytes:
524
"""Custom authentication response logic."""
525
# Implement custom authentication challenge response
526
prepared_password = self.prepare_password(password)
527
# Custom logic to combine with auth_data
528
return prepared_password
529
530
# Register custom plugin
531
auth_plugin_map = {
532
'custom_auth_plugin': CustomAuthPlugin
533
}
534
535
connection = mysql.connector.connect(
536
host='localhost',
537
user='custom_user',
538
password='custom_password',
539
database='mydatabase',
540
auth_plugin='custom_auth_plugin',
541
auth_plugin_map=auth_plugin_map
542
)
543
544
print("Custom authentication successful")
545
connection.close()
546
```
547
548
### Connection Security Best Practices
549
550
```python
551
import mysql.connector
552
553
# Comprehensive security configuration
554
secure_config = {
555
'host': 'mysql.example.com',
556
'port': 3306,
557
'user': 'secure_user',
558
'password': 'strong_password_123!',
559
'database': 'mydatabase',
560
561
# Authentication
562
'auth_plugin': 'caching_sha2_password',
563
564
# SSL/TLS security
565
'ssl_disabled': False,
566
'ssl_verify_cert': True,
567
'ssl_verify_identity': True,
568
'ssl_cert': '/path/to/client-cert.pem',
569
'ssl_key': '/path/to/client-key.pem',
570
'ssl_ca': '/path/to/ca-cert.pem',
571
'tls_versions': ['TLSv1.2', 'TLSv1.3'],
572
'tls_ciphersuites': [
573
'TLS_AES_256_GCM_SHA384',
574
'TLS_CHACHA20_POLY1305_SHA256'
575
],
576
577
# Connection security
578
'connect_timeout': 10,
579
'read_timeout': 30,
580
'write_timeout': 30,
581
'compress': False, # Disable compression for security
582
583
# Application security
584
'autocommit': False, # Explicit transaction management
585
'allow_local_infile': False, # Disable LOCAL INFILE for security
586
'allow_local_infile_in_path': None,
587
588
# Session security
589
'sql_mode': 'STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO'
590
}
591
592
try:
593
connection = mysql.connector.connect(**secure_config)
594
print("Secure connection established successfully")
595
596
# Verify connection security
597
cursor = connection.cursor()
598
cursor.execute("SHOW STATUS LIKE 'Ssl_cipher'")
599
result = cursor.fetchone()
600
if result:
601
print(f"SSL Cipher: {result[1]}")
602
603
cursor.execute("SELECT @@ssl_ca, @@ssl_cert, @@ssl_key")
604
ssl_info = cursor.fetchone()
605
print(f"SSL Configuration: CA={ssl_info[0]}, Cert={ssl_info[1]}, Key={ssl_info[2]}")
606
607
cursor.close()
608
connection.close()
609
610
except mysql.connector.Error as err:
611
print(f"Secure connection failed: {err}")
612
```
613
614
### Dynamic Authentication Plugin Selection
615
616
```python
617
import mysql.connector
618
619
def connect_with_fallback_auth(host: str, user: str, password: str, database: str):
620
"""Connect with authentication plugin fallback."""
621
622
# Try authentication methods in order of preference
623
auth_methods = [
624
'caching_sha2_password', # MySQL 8.0+ default
625
'mysql_native_password', # Legacy compatibility
626
'sha256_password' # SHA256 for secure environments
627
]
628
629
for auth_plugin in auth_methods:
630
try:
631
connection = mysql.connector.connect(
632
host=host,
633
user=user,
634
password=password,
635
database=database,
636
auth_plugin=auth_plugin,
637
ssl_disabled=False,
638
ssl_verify_cert=True
639
)
640
641
print(f"Connected successfully using {auth_plugin}")
642
return connection
643
644
except mysql.connector.Error as err:
645
print(f"Authentication with {auth_plugin} failed: {err}")
646
continue
647
648
raise mysql.connector.Error("All authentication methods failed")
649
650
# Usage
651
try:
652
connection = connect_with_fallback_auth(
653
host='localhost',
654
user='myuser',
655
password='mypassword',
656
database='mydatabase'
657
)
658
659
# Use connection
660
cursor = connection.cursor()
661
cursor.execute("SELECT 'Authentication successful' as message")
662
result = cursor.fetchone()
663
print(result[0])
664
665
cursor.close()
666
connection.close()
667
668
except mysql.connector.Error as err:
669
print(f"Connection failed: {err}")
670
```