You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: articles/app-service/tutorial-connect-app-access-sql-database-as-user-dotnet.md
+48-45Lines changed: 48 additions & 45 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,37 +4,38 @@ description: Secure database connectivity with Azure Active Directory authentica
4
4
5
5
ms.devlang: csharp
6
6
ms.topic: tutorial
7
-
ms.date: 03/07/2022
7
+
ms.date: 04/21/2023
8
8
---
9
9
# Tutorial: Connect an App Service app to SQL Database on behalf of the signed-in user
10
10
11
-
[App Service](overview.md) provides a highly scalable, self-patching web hosting service in Azure. It also provides [user authentication](overview-authentication-authorization.md)for your app, which is a turn-key solution for securing access to your app. Paired with the Azure Active Directory authentication provider, you're able to connect to any Azure service by impersonating the signed-in user (also known as the [on-behalf-of flow](../active-directory/develop/v2-oauth2-on-behalf-of-flow.md)) as long as the service supports Azure Active Directory authentication. This is a more advanced connectivity approach to [Tutorial: Access data with managed identity](tutorial-connect-msi-sql-database.md) and has the following advantages in enterprise scenarios:
11
+
This tutorial shows you how to enable [built-in authentication](overview-authentication-authorization.md)in an [App Service](overview.md)app using the Azure Active Directory authentication provider, then extend it by connecting it to a back-end Azure SQL Database by impersonating the signed-in user (also known as the [on-behalf-of flow](../active-directory/develop/v2-oauth2-on-behalf-of-flow.md)). This is a more advanced connectivity approach to [Tutorial: Access data with managed identity](tutorial-connect-msi-sql-database.md) and has the following advantages in enterprise scenarios:
12
12
13
13
- Eliminates connection secrets to back-end services, just like the managed identity approach.
14
-
- Gives the back-end service more control over who or how much to grant access to its data and functionality.
15
-
- Lets the app provide tailored data and functionality to the signed-in user.
14
+
- Gives the back-end database (or any other Azure service) more control over who or how much to grant access to its data and functionality.
15
+
- Lets the app tailor its data presentation to the signed-in user.
16
16
17
-
In this tutorial, you'll add Azure Active Directory authentication to the sample web app you built in one of the following tutorials:
17
+
In this tutorial, you'll add Azure Active Directory authentication to the sample web app you deployed in one of the following tutorials:
18
18
19
19
-[Tutorial: Build an ASP.NET app in Azure with Azure SQL Database](app-service-web-tutorial-dotnet-sqldatabase.md)
20
20
-[Tutorial: Build an ASP.NET Core and Azure SQL Database app in Azure App Service](tutorial-dotnetcore-sqldb-app.md)
21
21
22
-
When you're finished, your sample app will connect to SQL Database securely on behalf of the signed-in user.
22
+
When you're finished, your sample app will authenticate users connect to SQL Database securely on behalf of the signed-in user.
23
23
24
-

24
+
:::image type="content" source="./media/tutorial-connect-app-access-sql-database-as-user-dotnet/architecture.png" alt-text="Architecture diagram for tutorial scenario.":::
25
25
26
26
> [!NOTE]
27
27
> The steps covered in this tutorial support the following versions:
28
28
>
29
-
> - .NET Framework 4.8 and above
30
-
> - .NET 6.0 and above
29
+
> - .NET Framework 4.8 and higher
30
+
> - .NET 6.0 and higher
31
31
>
32
32
33
33
What you will learn:
34
34
35
35
> [!div class="checklist"]
36
-
> * Enable built-in authentication and authorization
37
-
> * Secure apps against unauthenticated requests
36
+
> * Enable built-in authentication for Azure SQL Database
37
+
> * Disable other authentication options in Azure SQL Database
38
+
> * Enable App Service authentication
38
39
> * Use Azure Active Directory as the identity provider
39
40
> * Access Azure SQL Database on behalf of the signed-in Azure AD user
40
41
@@ -54,18 +55,18 @@ If you haven't already, follow one of the two tutorials first. Alternatively, yo
## 1. Configure database server with Azure AD authentication
60
61
61
-
First, enable Azure Active Directory authentication to SQL Database by assigning an Azure AD user as the admin of the server. This user is different from the Microsoft account you used to sign up for your Azure subscription. It must be a user that you created, imported, synced, or invited into Azure AD. For more information on allowed Azure AD users, see [Azure AD features and limitations in SQL Database](../azure-sql/database/authentication-aad-overview.md#azure-ad-features-and-limitations).
62
+
First, enable Azure Active Directory authentication to SQL Database by assigning an Azure AD user as the admin of the server. This user is different from the Microsoft account you used to sign up for your Azure subscription. It must be a user that you created, imported, synced, or invited into Azure AD. For more information on allowed Azure AD users, see [Azure AD features and limitations in SQL Database](/azure/azure-sql/database/authentication-aad-overview#azure-ad-features-and-limitations).
62
63
63
64
1. If your Azure AD tenant doesn't have a user yet, create one by following the steps at [Add or delete users using Azure Active Directory](../active-directory/fundamentals/add-users-azure-active-directory.md).
64
65
65
66
1. Find the object ID of the Azure AD user using the [`az ad user list`](/cli/azure/ad/user#az_ad_user_list) and replace *\<user-principal-name>*. The result is saved to a variable.
66
67
67
68
```azurecli-interactive
68
-
azureaduser=$(az ad user list --filter "userPrincipalName eq '<user-principal-name>'" --query [].objectId --output tsv)
69
+
azureaduser=$(az ad user list --filter "userPrincipalName eq '<user-principal-name>'" --query [].id --output tsv)
69
70
```
70
71
71
72
> [!TIP]
@@ -75,7 +76,13 @@ First, enable Azure Active Directory authentication to SQL Database by assigning
75
76
1. Add this Azure AD user as an Active Directory admin using [`az sql server ad-admin create`](/cli/azure/sql/server/ad-admin#az_sql_server_ad_admin_create) command in the Cloud Shell. In the following command, replace *\<server-name>* with the server name (without the `.database.windows.net` suffix).
76
77
77
78
```azurecli-interactive
78
-
az sql server ad-admin create --resource-group myResourceGroup --server-name <server-name> --display-name ADMIN --object-id $azureaduser
79
+
az sql server ad-admin create --resource-group <group-name> --server-name <server-name> --display-name ADMIN --object-id $azureaduser
80
+
```
81
+
82
+
1. Restrict the database server authentication to Active Directory authentication. This step effectively disables SQL authentication.
83
+
84
+
```azurecli-interactive
85
+
az sql server ad-only-auth enable --resource-group <group-name> --server-name <server-name>
79
86
```
80
87
81
88
For more information on adding an Active Directory admin, see [Provision an Azure Active Directory administrator for your server](../azure-sql/database/authentication-aad-configure.md#provision-azure-ad-admin-sql-managed-instance)
@@ -86,20 +93,18 @@ You enable authentication with Azure Active Directory as the identity provider.
86
93
87
94
1. In the [Azure portal](https://portal.azure.com) menu, select **Resource groups** or search for and select *Resource groups* from any page.
88
95
89
-
1. In **Resource groups**, find and select your resource group. In **Overview**, select your app's management page.
90
-
91
-
:::image type="content" source="./media/tutorial-auth-aad/portal-navigate-back-end.png" alt-text="Screenshot of the Resource groups window, showing the Overview for an example resource group and an app's management page selected.":::
96
+
1. In **Resource groups**, find and select your resource group, then select your app.
92
97
93
98
1. In your app's left menu, select **Authentication**, and then select **Add identity provider**.
94
99
95
100
1. In the **Add an identity provider** page, select **Microsoft** as the **Identity provider** to sign in Microsoft and Azure AD identities.
96
101
97
102
1. Accept the default settings and select **Add**.
98
103
99
-
:::image type="content" source="./media/tutorial-auth-aad/configure-auth-back-end.png" alt-text="Screenshot of the app's left menu showing Authentication/Authorization selected and settings selected in the right menu.":::
104
+
:::image type="content" source="./media/tutorial-connect-app-access-sql-database-as-user-dotnet/add-aad-provider.png" alt-text="Screenshot showing the add identity provider page.":::
100
105
101
106
> [!TIP]
102
-
> If you run into errors and reconfigure your app's authentication/authorization settings, the tokens in the token store may not be regenerated from the new settings. To make sure your tokens are regenerated, you need to sign out and sign back in to your app. An easy way to do it is to use your browser in private mode, and close and reopen the browser in private mode after changing the settings in your apps.
107
+
> If you run into errors and reconfigure your app's authentication settings, the tokens in the token store may not be regenerated from the new settings. To make sure your tokens are regenerated, you need to sign out and sign back in to your app. An easy way to do it is to use your browser in private mode, and close and reopen the browser in private mode after changing the settings in your apps.
103
108
104
109
## 3. Configure user impersonation to SQL Database
105
110
@@ -113,7 +118,7 @@ Currently, your Azure app connects to SQL Database uses SQL authentication (user
113
118
114
119
1. In the **Request API permissions** page for Azure SQL Database, select **Delegated permissions** and **user_impersonation**, then select **Add permissions**.
115
120
116
-
:::image type="content" source="./media/tutorial-auth-aad/select-permission-front-end.png" alt-text="Screenshot of the Request API permissions page showing Delegated permissions, user_impersonation, and the Add permission button selected.":::
121
+
:::image type="content" source="./media/tutorial-connect-app-access-sql-database-as-user-dotnet/select-permission.png" alt-text="Screenshot of the Request API permissions page showing Delegated permissions, user_impersonation, and the Add permission button selected.":::
117
122
118
123
## 4. Configure App Service to return a usable access token
119
124
@@ -136,15 +141,9 @@ The commands effectively add a `loginParameters` property with additional custom
136
141
> [!TIP]
137
142
> To configure the required scopes using a web interface instead, see the Microsoft steps at [Refresh auth tokens](configure-authentication-oauth-tokens.md#refresh-auth-tokens).
138
143
139
-
140
144
Your apps are now configured. The app can now generate a token that SQL Database accepts.
141
145
142
-
## 5. Modify your project
143
-
144
-
> [!NOTE]
145
-
> **Microsoft.Azure.Services.AppAuthentication** is no longer recommended to use with new Azure SDK.
146
-
> It is replaced with new **Azure Identity client library** available for .NET, Java, TypeScript and Python and should be used for all new development.
147
-
> Information about how to migrate to `Azure Identity`can be found here: [AppAuthentication to Azure.Identity Migration Guidance](/dotnet/api/overview/azure/app-auth-migration).
146
+
## 5. Use the access token in your application code
148
147
149
148
The steps you follow for your project depends on whether you're using [Entity Framework](/ef/ef6/) (default for ASP.NET) or [Entity Framework Core](/ef/core/) (default for ASP.NET Core).
150
149
@@ -181,34 +180,37 @@ public MyDatabaseContext (DbContextOptions<MyDatabaseContext> options, IHttpCont
181
180
> [!NOTE]
182
181
> The code adds the access token supplied by App Service authentication to the connection object.
183
182
>
184
-
> This code change doesn't work locally. For more information, see [How do I debug locally when using App Service authentication?]().
183
+
> This code change doesn't work locally. For more information, see [How do I debug locally when using App Service authentication?](#how-do-i-debug-locally-when-using-app-service-authentication).
185
184
186
185
## 6. Publish your changes
187
186
188
-
1. In the previous tutorial, you set a connection string in App Service using SQL authentication, with a username and password. Use the following command to remove the connection secrets, but replace *\<group-name>*, *\<app-name>*, *\<db-server-name>*, and *\<db-name>* with yours.
187
+
# [ASP.NET](#tab/dotnet)
188
+
189
+
1.**If you came from [Tutorial: Build an ASP.NET app in Azure with SQL Database](app-service-web-tutorial-dotnet-sqldatabase.md)**, you set a connection string in App Service using SQL authentication, with a username and password. Use the following command to remove the connection secrets, but replace *\<group-name>*, *\<app-name>*, *\<db-server-name>*, and *\<db-name>* with yours.
189
190
190
191
```azurecli-interactive
191
192
az webapp config connection-string set --resource-group <group-name> --name <app-name> --type SQLAzure --settings MyDbConnection="server=tcp:<db-server-name>.database.windows.net;database=<db-name>;"
192
193
```
193
194
194
-
All that's left now is to publish your changes to Azure.
195
-
196
-
# [ASP.NET](#tab/dotnet)
197
-
198
-
1. **If you came from [Tutorial: Build an ASP.NET app in Azure with SQL Database](app-service-web-tutorial-dotnet-sqldatabase.md)**, publish your changes in Visual Studio. In the **Solution Explorer**, right-click your **DotNetAppSqlDb** project and select **Publish**.
195
+
1. Publish your changes in Visual Studio. In the **Solution Explorer**, right-click your **DotNetAppSqlDb** project and select **Publish**.
199
196
200
197

201
198
202
199
1. In the publish page, select **Publish**.
203
200
204
201
# [ASP.NET Core](#tab/dotnetcore)
205
202
206
-
**If you came from [Tutorial: Build an ASP.NET Core and SQL Database app in Azure App Service](tutorial-dotnetcore-sqldb-app.md)**, publish your changes using Git, with the following commands:
203
+
1.**If you came from [Tutorial: Build an ASP.NET Core and SQL Database app in Azure App Service](tutorial-dotnetcore-sqldb-app.md)**, you have a connection string called `defaultConnection` in App Service using SQL authentication, with a username and password. Use the following command to remove the connection secrets, but replace *\<group-name>*, *\<app-name>*, *\<db-server-name>*, and *\<db-name>* with yours.
207
204
208
-
```bash
209
-
git commit -am "OBO connect flow"
210
-
git push azure main
211
-
```
205
+
```azurecli-interactive
206
+
az webapp config connection-string set --resource-group <group-name> --name <app-name> --type SQLAzure --settings defaultConnection="server=tcp:<db-server-name>.database.windows.net;database=<db-name>;"
207
+
```
208
+
209
+
1. You would've made your code changes in your GitHub fork, with Visual Studio Code in the browser. From the left menue, select **Source Control**.
210
+
211
+
1. Type in a commit message like `OBO connect` and select **Commit**.
212
+
213
+
The commit will trigger a deployment to App Service. Wait a few minutes for the deployment to finish.
212
214
213
215
-----
214
216
@@ -251,9 +253,9 @@ The most common causes of this error are:
251
253
252
254
#### How do I debug locally when using App Service authentication?
253
255
254
-
Because App Service authentication is a feature in Azure, it's not possible for the same code to work in your local environment. Unlike the app running in Azure, your local code isn't connected to an Azure AD app registration. Neither is there any pre-built authentication logic that injects the access token likein App Service. You have a few alternatives:
256
+
Because App Service authentication is a feature in Azure, it's not possible for the same code to work in your local environment. Unlike the app running in Azure, your local code doesn't benefit from the authentication middleware from App Service. You have a few alternatives:
255
257
256
-
- Connect to SQL Database from your local environment with [`Active Directory Interactive`](https://docs.microsoft.com/sql/connect/ado-net/sql/azure-active-directory-authentication#using-active-directory-interactive-authentication). The authentication flow doesn't sign in the user to the app itself, but it does connect to the back-end database with the signed-in user, and allows you to test user authorization locally.
258
+
- Connect to SQL Database from your local environment with [`Active Directory Interactive`](/sql/connect/ado-net/sql/azure-active-directory-authentication#using-active-directory-interactive-authentication). The authentication flow doesn't sign in the user to the app itself, but it does connect to the back-end database with the signed-in user, and allows you to test database authorization locally.
257
259
- Manually copy the access token from `https://<app-name>.azurewebsites.net/.auth/me` into your code, in place of the `X-MS-TOKEN-AAD-ACCESS-TOKEN` request header.
258
260
- If you deploy from Visual Studio, use remote debugging of your App Service app.
259
261
@@ -266,8 +268,9 @@ Your access token expires after some time. For information on how to refresh you
266
268
What you learned:
267
269
268
270
> [!div class="checklist"]
269
-
>* Enable built-in authentication and authorization
270
-
>* Secure apps against unauthenticated requests
271
+
> * Enable built-in authentication for Azure SQL Database
272
+
> * Disable other authentication options in Azure SQL Database
273
+
> * Enable App Service authentication
271
274
> * Use Azure Active Directory as the identity provider
272
275
> * Access Azure SQL Database on behalf of the signed-in Azure AD user
0 commit comments