-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathazure_auth_example.py
More file actions
187 lines (157 loc) · 7.6 KB
/
Copy pathazure_auth_example.py
File metadata and controls
187 lines (157 loc) · 7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# Example usage of Azure credentials with FastMSSQL
import asyncio
import os
import fastmssql
async def test_service_principal_auth():
"""Test Service Principal authentication."""
print("Testing Service Principal authentication...")
# These would typically come from environment variables or secure configuration
azure_cred = fastmssql.AzureCredential.service_principal(
client_id=os.getenv("AZURE_CLIENT_ID", "your-client-id"),
client_secret=os.getenv("AZURE_CLIENT_SECRET", "your-client-secret"),
tenant_id=os.getenv("AZURE_TENANT_ID", "your-tenant-id")
)
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
result = await conn.query("SELECT GETDATE() as current_dt, USER_NAME() as user_name")
for row in result.rows():
print(f"Connected successfully! Current time: {row['current_dt']}, User: {row['user_name']}")
except Exception as e:
print(f"Service Principal authentication failed: {e}")
async def test_managed_identity_auth():
"""Test Managed Identity authentication (only works on Azure resources)."""
print("\nTesting Managed Identity authentication...")
azure_cred = fastmssql.AzureCredential.managed_identity(client_id=None)
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
result = await conn.query("SELECT GETDATE() as current_dt, USER_NAME() as user_name")
for row in result.rows():
print(f"Managed Identity connected! Current time: {row['current_dt']}, User: {row['user_name']}")
except Exception as e:
print(f"Managed Identity authentication failed (expected if not on Azure resource): {e}")
async def test_user_assigned_managed_identity():
"""Test User-Assigned Managed Identity authentication."""
print("\nTesting User-Assigned Managed Identity authentication...")
azure_cred = fastmssql.AzureCredential.managed_identity(
client_id=os.getenv("AZURE_USER_ASSIGNED_IDENTITY_CLIENT_ID")
)
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
result = await conn.query("SELECT GETDATE() as current_dt, USER_NAME() as user_name")
for row in result.rows():
print(f"User-Assigned MI connected! Current time: {row['current_dt']}, User: {row['user_name']}")
except Exception as e:
print(f"User-Assigned Managed Identity authentication failed: {e}")
async def test_access_token_auth():
"""Test pre-obtained access token authentication."""
print("\nTesting Access Token authentication...")
# In a real scenario, you would obtain this token from another Azure service
access_token = os.getenv("AZURE_ACCESS_TOKEN")
if not access_token:
print("AZURE_ACCESS_TOKEN environment variable not set, skipping test")
return
azure_cred = fastmssql.AzureCredential.access_token(access_token)
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
result = await conn.query("SELECT GETDATE() as current_dt, USER_NAME() as user_name")
for row in result.rows():
print(f"Access Token connected! Current time: {row['current_dt']}, User: {row['user_name']}")
except Exception as e:
print(f"Access Token authentication failed: {e}")
async def test_default_azure_auth():
"""Test Default Azure credential chain."""
print("\nTesting Default Azure credential chain...")
azure_cred = fastmssql.AzureCredential.default()
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
result = await conn.query("SELECT GETDATE() as current_dt, USER_NAME() as user_name")
for row in result.rows():
print(f"Default credential connected! Current time: {row['current_dt']}, User: {row['user_name']}")
except Exception as e:
print(f"Default Azure credential authentication failed: {e}")
async def test_database_operations():
"""Test various database operations with Azure authentication."""
print("\nTesting database operations with Azure authentication...")
azure_cred = fastmssql.AzureCredential.service_principal(
client_id=os.getenv("AZURE_CLIENT_ID", "your-client-id"),
client_secret=os.getenv("AZURE_CLIENT_SECRET", "your-client-secret"),
tenant_id=os.getenv("AZURE_TENANT_ID", "your-tenant-id")
)
try:
async with fastmssql.Connection(
server=os.getenv("AZURE_SQL_SERVER", "yourserver.database.windows.net"),
database=os.getenv("AZURE_SQL_DATABASE", "yourdatabase"),
azure_credential=azure_cred
) as conn:
# Test SELECT query
result = await conn.query(
"SELECT name, database_id FROM sys.databases WHERE database_id <= @P1",
[5]
)
print("Available databases:")
for row in result.rows():
print(f" - {row['name']} (ID: {row['database_id']})")
# Test connection pool statistics
stats = await conn.pool_stats()
print(f"\nConnection Pool Stats: {stats}")
except Exception as e:
print(f"Database operations failed: {e}")
async def main():
"""Run all Azure authentication tests."""
print("FastMSSSQL Azure Authentication Examples")
print("=" * 50)
# Check for environment variables
required_vars = {
'AZURE_CLIENT_ID': os.getenv('AZURE_CLIENT_ID'),
'AZURE_CLIENT_SECRET': os.getenv('AZURE_CLIENT_SECRET'),
'AZURE_TENANT_ID': os.getenv('AZURE_TENANT_ID'),
'AZURE_SQL_SERVER': os.getenv('AZURE_SQL_SERVER'),
'AZURE_SQL_DATABASE': os.getenv('AZURE_SQL_DATABASE')
}
print("Environment Variables:")
missing_vars = []
for var, value in required_vars.items():
if value:
display_value = '***' if 'SECRET' in var else value
print(f"✅ {var}: {display_value}")
else:
print(f"❌ {var}: Not set")
missing_vars.append(var)
if missing_vars:
print("\n⚠️ Missing environment variables:")
for var in missing_vars:
print(f" - {var}")
print("\n💡 To fix this, run: source azure.env")
print(" Then try running this script again.")
return
print("=" * 50)
# Run tests
await test_service_principal_auth()
await test_managed_identity_auth()
await test_user_assigned_managed_identity()
await test_access_token_auth()
await test_default_azure_auth()
await test_database_operations()
print("\nAzure authentication testing completed!")
if __name__ == "__main__":
asyncio.run(main())