Skip to content

Commit 3f4a1aa

Browse files
authored
Merge pull request #27069 from vmagelo/migration-guide-python
Create Python migration guide similar to .NET guide
2 parents 2f120c0 + 9e9f851 commit 3f4a1aa

12 files changed

Lines changed: 316 additions & 95 deletions
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
---
2+
title: Migrate a Python application to use passwordless connections with Azure SQL Database
3+
description: Learn how to connect to migrate a Python application to use passwordless connections with Azure SQL Database
4+
author: bobtabor-msft
5+
ms.author: rotabor
6+
ms.date: 05/15/2023
7+
ms.service: sql-database
8+
ms.subservice: security
9+
monikerRange: "= azuresql || = azuresql-db"
10+
ms.topic: how-to
11+
ms.custom: devx-track-csharp, passwordless-java, passwordless-js, passwordless-python, passwordless-dotnet, devx-track-azurecli, devx-track-azurepowershell
12+
ms.devlang: python
13+
---
14+
15+
# Migrate a Python application to use passwordless connections with Azure SQL Database
16+
17+
Application requests to Azure SQL Database must be authenticated. Although there are multiple options for authenticating to Azure SQL Database, you should prioritize passwordless connections in your applications when possible. Traditional authentication methods that use passwords or secret keys create security risks and complications. Visit the [passwordless connections for Azure services](/azure/developer/intro/passwordless-overview) hub to learn more about the advantages of moving to passwordless connections. The following tutorial explains how to migrate an existing Python application to connect to Azure SQL Database to use passwordless connections instead of a username and password solution.
18+
19+
## Configure the Azure SQL Database
20+
21+
[!INCLUDE [configure-the-azure-sql-database](../includes/passwordless/configure-the-azure-sql-database.md)]
22+
23+
## Configure your local development environment
24+
25+
Passwordless connections can be configured to work for both local and Azure hosted environments. In this section, you apply configurations to allow individual users to authenticate to Azure SQL Database for local development.
26+
27+
### Sign-in to Azure
28+
29+
[!INCLUDE [default-azure-credential-sign-in](../includes/passwordless/default-azure-credential-sign-in.md)]
30+
31+
### Create a database user and assign roles
32+
33+
Create a user in Azure SQL Database. The user should correspond to the Azure account you used to sign-in locally in the [Sign-in to Azure](#sign-in-to-azure) section.
34+
35+
[!INCLUDE [local-create-user-roles](../includes/passwordless/local-create-user-roles.md)]
36+
37+
### Update the local connection configuration
38+
39+
Existing application code that connects to Azure SQL Database using the [Python SQL Driver - pyodbc](/sql/connect/python/pyodbc/python-sql-driver-pyodbc) continues to work with passwordless connections with minor changes. For example, the following code works with both SQL authentication and passwordless connections when running locally and when deployed to Azure App Service.
40+
41+
```python
42+
connection_string = os.environ["AZURE_SQL_CONNECTIONSTRING"]
43+
44+
def get_all():
45+
with get_conn() as conn:
46+
cursor = conn.cursor()
47+
cursor.execute("SELECT * FROM Persons")
48+
# Do something with the data
49+
return
50+
51+
def get_conn():
52+
credential = identity.DefaultAzureCredential(exclude_interactive_browser_credential=False)
53+
token_bytes = credential.get_token("https://database.windows.net/.default").token.encode("UTF-16-LE")
54+
token_struct = struct.pack(f'<I{len(token_bytes)}s', len(token_bytes), token_bytes)
55+
SQL_COPT_SS_ACCESS_TOKEN = 1256 # This connection option is defined by microsoft in msodbcsql.h
56+
conn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})
57+
return conn
58+
```
59+
60+
> [!TIP]
61+
> In this example code, the App Service environment variable `WEBSITE_HOSTNAME` is used to determine what environment the code is running in. For other deployment scenarios, you can use other environment variables to determine the environment.
62+
63+
To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) for local development, use the passwordless connection string format:
64+
65+
```
66+
Driver={ODBC Driver 18 for SQL Server};Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30
67+
```
68+
69+
### Test the app
70+
71+
Run your app locally and verify that the connections to Azure SQL Database are working as expected. Keep in mind that it may take several minutes for changes to Azure users and roles to propagate through your Azure environment. Your application is now configured to run locally without developers having to manage secrets in the application itself.
72+
73+
## Configure the Azure hosting environment
74+
75+
Once your app is configured to use passwordless connections locally, the same code can authenticate to Azure SQL Database after it's deployed to Azure. The sections that follow explain how to configure a deployed application to connect to Azure SQL Database using a [managed identity](/azure/active-directory/managed-identities-azure-resources/overview). Managed identities provide an automatically managed identity in Azure Active Directory (Azure AD) for applications to use when connecting to resources that support Azure AD authentication. Learn more about managed identities:
76+
77+
- [Passwordless overview](/azure/developer/intro/passwordless-overview)
78+
- [Managed identity best practices](/azure/active-directory/managed-identities-azure-resources/managed-identity-best-practice-recommendations)
79+
80+
### Create the managed identity
81+
82+
[!INCLUDE [create-the-managed-identity](../includes/passwordless/create-the-managed-identity.md)]
83+
84+
## Associate the managed identity with your web app
85+
86+
Configure your web app to use the user-assigned managed identity you created.
87+
88+
# [Azure portal](#tab/azure-portal-assign)
89+
90+
Complete the following steps in the Azure portal to associate the user-assigned managed identity with your app. These same steps apply to the following Azure services:
91+
92+
* Azure Spring Apps
93+
* Azure Container Apps
94+
* Azure virtual machines
95+
* Azure Kubernetes Service
96+
* Navigate to the overview page of your web app.
97+
98+
1) Select **Identity** from the left navigation.
99+
100+
1) On the **Identity** page, switch to the **User assigned** tab.
101+
102+
1) Select **+ Add** to open the **Add user assigned managed identity** flyout.
103+
104+
1) Select the subscription you used previously to create the identity.
105+
106+
1) Search for the **MigrationIdentity** by name and select it from the search results.
107+
108+
1) Select **Add** to associate the identity with your app.
109+
110+
:::image type="content" source="media/passwordless-connections/assign-managed-identity-small.png" lightbox="media/passwordless-connections/assign-managed-identity.png" alt-text="A screenshot showing how to assign a managed identity.":::
111+
112+
# [Azure CLI](#tab/azure-cli-assign)
113+
114+
[!INCLUDE [associate-managed-identity-cli](../includes/passwordless/associate-managed-identity-cli.md)]
115+
116+
---
117+
118+
### Create a database user for the identity and assign roles
119+
120+
[!INCLUDE [create-database-user-for-identity](../includes/passwordless/create-database-user-for-identity.md)]
121+
122+
### Update the connection string
123+
124+
Update your Azure app configuration to use the passwordless connection string format. The format should be the same used in your local environment.
125+
126+
Connection strings can be stored as environment variables in your app hosting environment. The following instructions focus on App Service, but other Azure hosting services provide similar configurations.
127+
128+
```
129+
Driver={ODBC Driver 18 for SQL Server};Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30
130+
```
131+
132+
`<database-server-name>` is the name of your Azure SQL Database server and `<database-name>` is the name of your Azure SQL Database.
133+
134+
### Create an app setting for the managed identity client ID
135+
136+
To use the user-assigned managed identity, create an AZURE_CLIENT_ID environment variable and set it equal to the client ID of the managed identity. You can set this variable in the **Configuration** section of your app in the Azure portal. You can find the client ID in the **Overview** section of the managed identity resource in the Azure portal.
137+
138+
Save your changes and restart the application if it doesn't do so automatically.
139+
140+
> [!NOTE]
141+
> The example connection code shown in this migration guide uses the [DefaultAzureCredential](/python/api/azure-identity/azure.identity.defaultazurecredential) class when deployed. Specifically, it uses the DefaultAzureCredential without passing the user-assigned managed identity client ID to the constructor. In this scenario, the fallback is to check for the AZURE_CLIENT_ID environment variable. If the AZURE_CLIENT_ID environment variable doesn't exist, a system-assigned managed identity will be used if configured.
142+
>
143+
> If you pass the managed identity client ID in the DefaultAzureCredential constructor, the connection code can still be used locally and deployed because the authentication process falls back to interactive authentication in the local scenario. For more information, see the [Azure Identity client library for Python](/python/api/overview/azure/identity-readme#defaultazurecredential).
144+
145+
### Test the application
146+
147+
Test your app to make sure everything is still working. It may take a few minutes for all of the changes to propagate through your Azure environment.
148+
149+
## Next steps
150+
151+
In this tutorial, you learned how to migrate an application to passwordless connections.
152+
153+
You can read the following resources to explore the concepts discussed in this article in more depth:
154+
155+
- [Passwordless overview](/azure/developer/intro/passwordless-overview)
156+
- [Managed identity best practices](/azure/active-directory/managed-identities-azure-resources/managed-identity-best-practice-recommendations)
157+
- [Tutorial: Secure a database in Azure SQL Database](/azure/azure-sql/database/secure-database-tutorial)
158+
- [Authorize database access to SQL Database](/azure/azure-sql/database/logins-create-manage)

‎azure-sql/database/azure-sql-passwordless-migration.md‎

Lines changed: 8 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,7 @@ Application requests to Azure SQL Database must be authenticated. Although there
1818

1919
## Configure the Azure SQL Database
2020

21-
Passwordless connections use Azure Active Directory (Azure AD) authentication to connect to Azure services, including Azure SQL Database. With Azure AD authentication, you can manage identities in a central location to simplify permission management. Learn more about configuring Azure AD authentication for your Azure SQL Database:
22-
23-
- [Azure AD authentication overview](/azure/azure-sql/database/authentication-aad-overview)
24-
- [Configure Azure AD auth](/azure/azure-sql/database/authentication-aad-configure)
25-
26-
For this migration guide, ensure you have an Azure AD admin assigned to your Azure SQL Database.
27-
28-
1) Navigate to the **Azure Active Directory** page of your logical server.
29-
30-
1) Select **Set admin**.
31-
32-
1) In the **Azure Active Directory** flyout menu, search for the user you want to assign as admin.
33-
34-
1) Select the user and choose **Select**.
35-
36-
:::image type="content" source="media/passwordless-connections/migration-enable-active-directory-small.png" lightbox="media/passwordless-connections/migration-enable-active-directory.png" alt-text="A screenshot showing how to enable active directory admin.":::
21+
[!INCLUDE [configure-the-azure-sql-database](../includes/passwordless/configure-the-azure-sql-database.md)]
3722

3823
## Configure your local development environment
3924

@@ -47,21 +32,7 @@ Passwordless connections can be configured to work for both local and Azure host
4732

4833
Create a user in Azure SQL Database. The user should correspond to the Azure account you used to sign-in locally via development tools like Visual Studio or IntelliJ.
4934

50-
1) In the Azure portal, browse to your SQL database and select **Query editor (preview)**.
51-
52-
2) Select **Continue as `<your-username>`** on the right side of the screen to sign into the database using your account.
53-
54-
3) On the query editor view, run the following T-SQL commands:
55-
56-
```sql
57-
CREATE USER <user@domain> FROM EXTERNAL PROVIDER;
58-
ALTER ROLE db_datareader ADD MEMBER <user@domain>;
59-
ALTER ROLE db_datawriter ADD MEMBER <user@domain>;
60-
ALTER ROLE db_ddladmin ADD MEMBER <user@domain>;
61-
GO
62-
```
63-
64-
:::image type="content" source="media/passwordless-connections/query-editor-user-small.png" lightbox="media/passwordless-connections/query-editor-user.png" alt-text="A screenshot showing how to use the Azure Query editor.":::
35+
[!INCLUDE [local-create-user-roles](../includes/passwordless/local-create-user-roles.md)]
6536

6637
### Update the local connection configuration
6738

@@ -87,8 +58,8 @@ To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) to use
8758
2. Replace the connection string value with the following passwordless format. Update the `<database-server-name>` and `<database-name>` placeholders with your own values:
8859

8960
```json
90-
"Server=tcp:<database-server-name>.database.windows.net,1433;Initial Catalog=<database-name>;
91-
Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication=\"Active Directory Default\";"
61+
Server=tcp:<database-server-name>.database.windows.net,1433;Initial Catalog=<database-name>;
62+
Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication="Active Directory Default";
9263
```
9364

9465
### Test the app
@@ -104,33 +75,7 @@ Once your app is configured to use passwordless connections locally, the same co
10475

10576
### Create the managed identity
10677

107-
Create a user-assigned managed identity using the Azure portal or the Azure CLI. Your application uses the identity to authenticate to other services.
108-
109-
# [Azure portal](#tab/azure-portal-create)
110-
111-
1. At the top of the Azure portal, search for *Managed identities*. Select the **Managed Identities** result.
112-
1. Select **+ Create** at the top of the **Managed Identities** overview page.
113-
1. On the **Basics** tab, enter the following values:
114-
* **Subscription**: Select your desired subscription.
115-
* **Resource Group**: Select your desired resource group.
116-
* **Region**: Select a region near your location.
117-
* **Name**: Enter a recognizable name for your identity, such as *MigrationIdentity*.
118-
1. Select **Review + create** at the bottom of the page.
119-
1. When the validation checks finish, select **Create**. Azure creates a new user-assigned identity.
120-
121-
After the resource is created, select **Go to resource** to view the details of the managed identity.
122-
123-
:::image type="content" source="media/passwordless-connections/create-managed-identity-portal-small.png" lightbox="media/passwordless-connections/create-managed-identity-portal.png" alt-text="A screenshot showing how to create a managed identity using the Azure portal.":::
124-
125-
# [Azure CLI](#tab/azure-cli-create)
126-
127-
Use the [az identity create](/cli/azure/identity) command to create a user-assigned managed identity:
128-
129-
```azurecli
130-
az identity create --name MigrationIdentity --resource-group <resource-group>
131-
```
132-
133-
---
78+
[!INCLUDE [create-the-managed-identity](../includes/passwordless/create-the-managed-identity.md)]
13479

13580
## Associate the managed identity with your web app
13681

@@ -172,33 +117,7 @@ Complete the following steps in the Azure portal to associate the user-assigned
172117

173118
### Create a database user for the identity and assign roles
174119

175-
Create a SQL database user that maps back to the user-assigned managed identity. Assign the necessary SQL roles to the user to allow your app to read, write, and modify the data and schema of your database.
176-
177-
1) In the Azure portal, browse to your SQL database and select **Query editor (preview)**.
178-
179-
2) Select **Continue as `<username>`** on the right side of the screen to sign into the database using your account.
180-
181-
3) On the query editor view, run the following T-SQL commands:
182-
183-
```sql
184-
CREATE USER <user-assigned-identity-name> FROM EXTERNAL PROVIDER;
185-
ALTER ROLE db_datareader ADD MEMBER <user-assigned-identity-name>;
186-
ALTER ROLE db_datawriter ADD MEMBER <user-assigned-identity-name>;
187-
ALTER ROLE db_ddladmin ADD MEMBER <user-assigned-identity-name>;
188-
GO
189-
```
190-
191-
:::image type="content" source="media/passwordless-connections/query-editor-identity-small.png" lightbox="media/passwordless-connections/query-editor-identity.png" alt-text="A screenshot showing how to use the Azure Query editor to create a SQL user for a managed identity.":::
192-
193-
---
194-
195-
> [!IMPORTANT]
196-
> Use caution when assigning database user roles in enterprise production environments. In those scenarios, the app shouldn't perform all operations using a single, elevated identity. Try to implement the principle of least privilege by configuring multiple identities with specific permissions for specific tasks.
197-
>
198-
> You can read more about configuring database roles and security on the following resources:
199-
>
200-
> * [Tutorial: Secure a database in Azure SQL Database](/azure/azure-sql/database/secure-database-tutorial)
201-
> * [Authorize database access to SQL Database](/azure/azure-sql/database/logins-create-manage)
120+
[!INCLUDE [create-database-user-for-identity](../includes/passwordless/create-database-user-for-identity.md)]
202121

203122
### Update the connection string
204123

@@ -209,8 +128,8 @@ Update your Azure app configuration to use the passwordless connection string fo
209128
1. Select the edit icon and update the connection string value to match following format. Change the `<database-server-name>` and `<database-name>` placeholders with the values of your own service.
210129

211130
```json
212-
"Server=tcp:<database-server-name>.database.windows.net,1433;Initial Catalog=<database-name>;
213-
Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication=\"Active Directory Default\";"
131+
Server=tcp:<database-server-name>.database.windows.net,1433;Initial Catalog=<database-name>;
132+
Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication="Active Directory Default";
214133
```
215134

216135
1. Save your changes and restart the application if it does not do so automatically.
-15.8 KB
Loading
5.06 KB
Loading
-17.3 KB
Loading
2.84 KB
Loading

0 commit comments

Comments
 (0)