|
| 1 | +--- |
| 2 | +title: "Using Azure Active Directory authentication with SqlClient" |
| 3 | +description: "Describes how to use supported Azure Active Directory authentication modes to connect to Azure SQL data sources with SqlClient" |
| 4 | +ms.date: "11/10/2020" |
| 5 | +dev_langs: |
| 6 | + - "csharp" |
| 7 | +ms.prod: sql |
| 8 | +ms.prod_service: connectivity |
| 9 | +ms.technology: connectivity |
| 10 | +ms.topic: conceptual |
| 11 | +author: karinazhou |
| 12 | +ms.author: v-jizho2 |
| 13 | +ms.reviewer: |
| 14 | +--- |
| 15 | + |
| 16 | +# Using Azure Active Directory authentication with SqlClient |
| 17 | + |
| 18 | +[!INCLUDE [appliesto-netfx-netcore-netst-md](../../../includes/appliesto-netfx-netcore-netst-md.md)] |
| 19 | + |
| 20 | +[!INCLUDE [Driver_ADONET_Download](../../../includes/driver_adonet_download.md)] |
| 21 | + |
| 22 | +This article describes how to connect to Azure SQL data sources using Azure Active Directory authentication from a .NET application with SqlClient. |
| 23 | + |
| 24 | +Azure Active Directory (Azure AD) authentication uses identities in Azure Active Directory to access Azure SQL data sources such as Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics. **Microsoft.Data.SqlClient** allows client applications to specify Azure AD credentials in different authentication modes when connecting to Azure SQL Database. By setting the `Authentication` connection property in the connection string, the client can choose a preferred Azure AD authentication mode according to the value provided. For more information about Azure AD authentication, see [Connecting to SQL Database By Using Azure Active Directory authentication](/azure/azure-sql/database/authentication-aad-overview). |
| 25 | + |
| 26 | +The early **Microsoft.Data.SqlClient** supports `Active Directory Password` for .NET Framework, .NET Core, and .NET Standard. It also supports `Active Directory Integrated` authentication and `Active Directory Interactive` authentication for .NET Framework. Starting with **Microsoft.Data.SqlClient** 2.0.0, support for `Active Directory Integrated authentication` and `Active Directory Interactive` authentication has been extended across .NET Framework, .NET Core, and .NET Standard. A new `Active Directory Service Principal` authentication mode is also added in SqlClient 2.0.0 that makes use of the client ID and secret of a service principal identity to accomplish authentication. More authentication modes are added in SqlClient 2.1.0 including `Active Directory Device Code Flow` and `Active Directory Managed Identity` (also known as `Active Directory MSI`). These new modes enable the application to acquire an access token to connect to the server. More information about all the Active Directory authentications are covered in the following sections. |
| 27 | + |
| 28 | + |
| 29 | +## Setting Azure Active Directory authentication in the connection string |
| 30 | + |
| 31 | +When connecting to Azure SQL data sources with Azure AD authentication, the application needs to provide a valid authentication mode. This table lists the supported authentication modes, which can be specified with the `Authentication` connection property. |
| 32 | + |
| 33 | +| Value | Description | Framework | Microsoft.Data.SqlClient Version | |
| 34 | +|:--|:--|:--|:--:| |
| 35 | +| Active Directory Password | Authenticate with an Azure AD identity using a username and password | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 1.0+| |
| 36 | +| Active Directory Integrated |Authenticate with an Azure AD identity using integrated authentication | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 2.0.0+<sup>1</sup> | |
| 37 | +| Active Directory Interactive | Authenticate with an Azure AD identity using interactive authentication | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 2.0.0+<sup>1</sup> | |
| 38 | +| Active Directory Service Principal | Authenticate with an Azure AD identity using the client ID and secret of a service principal identity | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 2.0.0+ | |
| 39 | +| Active Directory Device Code Flow | Authenticate with an Azure AD identity using Device Code Flow mode | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 2.1.0+ | |
| 40 | +| Active Directory Managed Identity, <br>Active Directory MSI | Authenticate with an Azure AD identity using system-assigned or user-assigned managed identity | .NET Framework 4.6+, .NET Core 2.1+, .NET Standard 2.0+ | 2.1.0+ | |
| 41 | + |
| 42 | +> [!NOTE] |
| 43 | +> <sup>1</sup> Before **Microsoft.Data.SqlClient** 2.0.0, `Active Directory Integrated` and `Active Directory Interactive` authentications are only supported on .NET Framework 4.6+. |
| 44 | +
|
| 45 | + |
| 46 | +## Connecting with Active Directory Password authentication |
| 47 | + |
| 48 | +`Active Directory Password` authentication mode supports authentication to Azure data sources with Azure AD for native or federated Azure AD users. When using this mode, user credentials must be provided in the connection string. The following example shows how to use `Active Directory Password` authentication. |
| 49 | + |
| 50 | +```c# |
| 51 | +// Use your own Server, Database, User Id, and Password. |
| 52 | +string ConnectionString = @"Server=demo.database.windows.net; Authentication=Active Directory Password; Database=testdb; User Id=user@domain.com; Password=***"; |
| 53 | + |
| 54 | +using (SqlConnection conn = new SqlConnection(ConnectionString)) { |
| 55 | + conn.Open(); |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | + |
| 60 | +## Connecting with Active Directory Integrated authentication |
| 61 | + |
| 62 | +To use `Active Directory Integrated` authentication mode, you need to federate the on-premise Active Directory with Azure AD in the cloud. Federation can be done using Active Directory Federation Services (ADFS), for example. When logged in to a domain-joined machine, you can access Azure SQL data sources without being prompted for credentials with this mode. Username and password cannot be specified in the connection string for .NET framework applications. Username is optional in the connection string for .NET Core and .NET Standard applications. The Credential property of SqlConnection cannot be set in this mode. The following code snippet is an example of when `Active Directory Integrated` authentication is in use. |
| 63 | + |
| 64 | +```c# |
| 65 | +// Use your own Server and Database. |
| 66 | +string ConnectionString1 = @"Server=demo.database.windows.net; Authentication=Active Directory Integrated; Database=testdb"; |
| 67 | + |
| 68 | +using (SqlConnection conn = new SqlConnection(ConnectionString1)) { |
| 69 | + conn.Open(); |
| 70 | +} |
| 71 | + |
| 72 | +// User Id is optional for .NET Core and .NET Standard |
| 73 | +string ConnectionString2 = @"Server=demo.database.windows.net; Authentication=Active Directory Integrated; Database=testdb; User Id=user@domain.com"; |
| 74 | + |
| 75 | +using (SqlConnection conn = new SqlConnection(ConnectionString2)) { |
| 76 | + conn.Open(); |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | + |
| 81 | +## Connecting with Active Directory Interactive authentication |
| 82 | + |
| 83 | +`Active Directory Interactive` authentication supports multi-factor authentication technology to connect to Azure SQL data sources. If this authentication mode is provided in the connection string, an Azure authentication screen will be displayed and ask the user to enter valid credentials. The password cannot be specified in the connection string. The Credential property of SqlConnection cannot be set in this mode. With **Microsoft.Data.SqlClient** 2.0.0 and above, username is allowed in the connection string when in interactive mode. The following example displays how to use `Active Directory Interactive` authentication. |
| 84 | + |
| 85 | +```c# |
| 86 | +// Use your own Server, Database, and User Id. |
| 87 | +// User Id is optional. |
| 88 | +string ConnectionString1 = @"Server=demo.database.windows.net; Authentication=Active Directory Interactive; Database=testdb; User Id=user@domain.com"; |
| 89 | + |
| 90 | +using (SqlConnection conn = new SqlConnection(ConnectionString1)) { |
| 91 | + conn.Open(); |
| 92 | +} |
| 93 | + |
| 94 | +// User Id is not provided. |
| 95 | +string ConnectionString2 = @"Server=demo.database.windows.net; Authentication=Active Directory Interactive; Database=testdb"; |
| 96 | + |
| 97 | +using (SqlConnection conn = new SqlConnection(ConnectionString2)) { |
| 98 | + conn.Open(); |
| 99 | +} |
| 100 | +``` |
| 101 | + |
| 102 | + |
| 103 | +## Connecting with Active Directory Service Principal authentication |
| 104 | + |
| 105 | +In `Active Directory Service Principal` authentication mode, the client application can connect to Azure SQL data sources by providing the client ID and secret of a service principal identity. Service Principal authentication involves setting up an App registration with a secret, granting permissions to the App in the Azure SQL Database instance, and then connecting with the correct credential. The following example shows how to use `Active Directory Service Principal` authentication. |
| 106 | + |
| 107 | +```c# |
| 108 | +// Use your own Server, Database, AppId , and secret. |
| 109 | +string ConnectionString = @"Server=demo.database.windows.net; Authentication=Active Directory Service Principal; Database=testdb; User Id=AppId; Password=secret"; |
| 110 | + |
| 111 | +using (SqlConnection conn = new SqlConnection(ConnectionString)) { |
| 112 | + conn.Open(); |
| 113 | +} |
| 114 | +``` |
| 115 | + |
| 116 | + |
| 117 | +## Connecting with Active Directory Device Code Flow authentication |
| 118 | + |
| 119 | +With [Microsoft Authentication Library](/azure/active-directory/develop/msal-overview) for .NET (MSAL.NET), `Active Directory Device Code Flow` authentication enables the client application to connect to Azure SQL data sources from devices and operating systems that do not have an interactive web browser. Interactive authentication will be performed on another device. For more information about device code flow authentication, see [OAuth2.0 Device Code Flow](/azure/active-directory/develop/v2-oauth2-device-code). When this mode is in use, the Credential property of SqlConnection cannot be set. Also, the username and password must not be specified in the connection string. The following code snippet is an example of using `Active Directory Device Code Flow` authentication. |
| 120 | + |
| 121 | +```c# |
| 122 | +// Use your own Server and Database. |
| 123 | +string ConnectionString = @"Server=demo.database.windows.net; Authentication=Active Directory Device Code Flow; Database=testdb"; |
| 124 | + |
| 125 | +using (SqlConnection conn = new SqlConnection(ConnectionString)) { |
| 126 | + conn.Open(); |
| 127 | +} |
| 128 | +``` |
| 129 | + |
| 130 | + |
| 131 | +## Connecting with Active Directory Managed Identity authentication |
| 132 | + |
| 133 | +**Managed Identities** for Azure resources is the new name for the service formerly known as **Managed Service Identity (MSI)**. When a client application uses an Azure resources to access an Azure service that support Azure AD authentication, **Managed Identities** can be used to authenticate by providing an identity for the Azure resource in Azure AD and use it to obtain access tokens. This can eliminate the need for developers having to manage credentials and secrets. There are two types of **Managed Identities**: _System-assigned Managed Identity_ and _User-assigned Managed Identity_. The _System-assigned Managed Identity_ is an identity created on a service instance in Azure AD. It is tied to the lifecycle of that service instance. _User-assigned Managed Identity_ is created as a standalone Azure resource. It can be assigned to one or more instances of an Azure service. For more information about **Managed Identities**, see [About managed identities for Azure resources](/azure/active-directory/managed-identities-azure-resources/overview). |
| 134 | + |
| 135 | +Since **Microsoft.Data.SqlClient** 2.1.0, the driver now supports authentication to Azure SQL Database, Azure Synapse, and Azure SQL Managed Instance by acquiring access tokens via Managed Identity. To use this authentication, specify either `Active Directory Managed Identity` or `Active Directory MSI` in the connection string and no password is required. The Credential property of SqlConnection cannot be set in this mode either. For _User-assigned Managed Identity_, username must be provided. The following example shows how to use `Active Directory Managed Identity` authentication with _System-assigned Managed Identity_. |
| 136 | + |
| 137 | +```c# |
| 138 | +// For System Assigned Managed Identity |
| 139 | +// Use your own Server and Database. |
| 140 | +string ConnectionString1 = @"Server=demo.database.windows.net; Authentication=Active Directory Managed Identity; Database=testdb"; |
| 141 | + |
| 142 | +using (SqlConnection conn = new SqlConnection(ConnectionString1)) { |
| 143 | + conn.Open(); |
| 144 | +} |
| 145 | + |
| 146 | +string ConnectionString2 = @"Server=demo.database.windows.net; Authentication=Active Directory MSI; Database=testdb"; |
| 147 | + |
| 148 | +using (SqlConnection conn = new SqlConnection(ConnectionString2)) { |
| 149 | + conn.Open(); |
| 150 | +} |
| 151 | +``` |
| 152 | + |
| 153 | +The following example demonstrates `Active Directory Managed Identity` authentication with a _User-assigned Managed Identity_. |
| 154 | + |
| 155 | +```c# |
| 156 | +// For User Assigned Managed Identity |
| 157 | +// Use your own Server, Database, and User Id. |
| 158 | +string ConnectionString1 = @"Server=demo.database.windows.net; Authentication=Active Directory Managed Identity; User Id=ObjectIdOfManagedIdentity; Database=testdb"; |
| 159 | + |
| 160 | +using (SqlConnection conn = new SqlConnection(ConnectionString1)) { |
| 161 | + conn.Open(); |
| 162 | +} |
| 163 | + |
| 164 | +string ConnectionString2 = @"Server=demo.database.windows.net; Authentication=Active Directory MSI; User Id=ObjectIdOfManagedIdentity; Database=testdb"; |
| 165 | + |
| 166 | +using (SqlConnection conn = new SqlConnection(ConnectionString2)) { |
| 167 | + conn.Open(); |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | + |
| 172 | +## Customizing Active Directory authentication with ActiveDirectoryAuthenticationProvider class |
| 173 | + |
| 174 | +Besides using the Active Directory authentication built into the driver, **Microsoft.Data.SqlClient** 2.1.0 and later provide applications the option to customize AD authentication. The customization is based on the _ActiveDirectoryAuthenticationProvider_ class, which is derived from the [_SqlAuthenticationProvider_](/dotnet/api/system.data.sqlclient.sqlauthenticationprovider) abstract class. During Active Directory authentication, the client application can define its own _ActiveDirectoryAuthencationProvider_ by either using a customized callback method or passing `Application Client Id` to the MSAL library via SqlClient driver for fetching access tokens. |
| 175 | + |
| 176 | +The following example displays how to use a custom callback when `Active Directory Device Code Flow` authentication is in use. |
| 177 | + |
| 178 | +[!code-csharp [AADAuthenticationCustomDeviceFlowCallback#1](~/../sqlclient/doc/samples/AADAuthenticationCustomDeviceFlowCallback.cs#1)] |
| 179 | + |
| 180 | +With a customized _ActiveDirectoryAuthenticationProvider_, a user-defined "Application Client Id" can be passed to SqlClient when a supported Active Directory authentication mode<sup>1</sup> is in use. The "Application Client Id" is also configurable via `SqlAuthenticationProviderConfigurationSection` or `SqlClientAuthenticationProviderConfigurationSection`<sup>2</sup>. |
| 181 | + |
| 182 | +> [!NOTE] |
| 183 | +> |
| 184 | +> <sup>1</sup> Supported AD authentication modes include `Active Directory Password`, `Active Directory Integrated`, `Active Directory Interactive`, `Active Directory Service Principal`, and `Active Directory Device Code Flow`. |
| 185 | +> |
| 186 | +> <sup>2</sup> The configuration property `applicationClientId` applies to .NET Frameowrk 4.6+ and .NET Core 2.1+. |
| 187 | +
|
| 188 | +The following code snippet is an example of using a customized _ActiveDirectoryAuthenticationProvider_ with a user-defined application client ID when `Active Directory Interactive` authentication is in use. |
| 189 | + |
| 190 | +[!code-csharp [ApplicationClientIdAzureAuthenticationProvider#1](~/../sqlclient/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs#1)] |
| 191 | + |
| 192 | +The following example shows how to set an application client ID via a configuration section. |
| 193 | + |
| 194 | +```xml |
| 195 | +<configuration> |
| 196 | + <configSections> |
| 197 | + <section name="SqlClientAuthenticationProviders" |
| 198 | + type="Microsoft.Data.SqlClient.SqlClientAuthenticationProviderConfigurationSection, Microsoft.Data.SqlClient" /> |
| 199 | + </configSections> |
| 200 | + <SqlClientAuthenticationProviders applicationClientId ="<GUID>" /> |
| 201 | +</configuration> |
| 202 | + |
| 203 | +<!--or--> |
| 204 | + |
| 205 | +<configuration> |
| 206 | + <configSections> |
| 207 | + <section name="SqlAuthenticationProviders" |
| 208 | + type="Microsoft.Data.SqlClient.SqlAuthenticationProviderConfigurationSection, Microsoft.Data.SqlClient" /> |
| 209 | + </configSections> |
| 210 | + <SqlAuthenticationProviders applicationClientId ="<GUID>" /> |
| 211 | +</configuration> |
| 212 | +``` |
| 213 | + |
| 214 | +## Custom SQL Authentication Provider support |
| 215 | + |
| 216 | +Given more flexibility, the client application can also use its own provider for AD authentication instead of using the _ActiveDirectoryAuthenticationProvider_ class. The custom authentication provider needs to be a subclass of _SqlAuthenticationProvider_ with overridden methods. The following example displays how to use a new authentication provider for `Active Directory Device Code Flow` authentication. |
| 217 | + |
| 218 | +[!code-csharp [CustomDeviceCodeFlowAzureAuthenticationProvider#1](~/../sqlclient/doc/samples/CustomDeviceCodeFlowAzureAuthenticationProvider.cs#1)] |
| 219 | + |
| 220 | +In addition, to improving the `Active Directory Interactive` authentication experience, Microsoft.Data.SqlClient 2.1.0 and later provides the following APIs for client applications to customize interactive and device code flow authentication. |
| 221 | + |
| 222 | +```c# |
| 223 | +public class ActiveDirectoryAuthenticationProvider |
| 224 | +{ |
| 225 | + // For .NET Framework targeted applications only |
| 226 | + // Sets a reference to the current System.Windows.Forms.IWin32Window that triggers the browser to be shown. |
| 227 | + // Used to center the browser pop-up onto this window. |
| 228 | + public void SetIWin32WindowFunc(Func<IWin32Window> iWin32WindowFunc); |
| 229 | + |
| 230 | + // For .NET Standard targeted applications only |
| 231 | + // Sets a reference to the ViewController (if using Xamarin.iOS), Activity (if using Xamarin.Android) IWin32Window or IntPtr (if using .NET Framework). |
| 232 | + // Used for invoking the browser for Active Directory Interactive authentication. |
| 233 | + public void SetParentActivityOrWindowFunc(Func<object> parentActivityOrWindowFunc); |
| 234 | + |
| 235 | + // For .NET Framework, .NET Core and .NET Standard targeted applications |
| 236 | + // Sets a callback method which is invoked with a custom Web UI instance that will let the user sign-in with Azure Active Directory, present consent if needed, and get back the authorization code. |
| 237 | + // Applicable when working with Active Directory Interactive authentication. |
| 238 | + public void SetAcquireAuthorizationCodeAsyncCallback(Func<Uri, Uri, CancellationToken, Task<Uri>> acquireAuthorizationCodeAsyncCallback); |
| 239 | + |
| 240 | + // For .NET Framework, .NET Core and .NET Standard targeted applications |
| 241 | + // Clears cached user tokens from the token provider. |
| 242 | + public static void ClearUserTokenCache(); |
| 243 | +} |
| 244 | +``` |
| 245 | + |
| 246 | + |
| 247 | +## See Also |
| 248 | +- [Application and service principal objects in Azure Active Directory](/azure/active-directory/develop/app-objects-and-service-principals) |
| 249 | +- [Authentication flows](/azure/active-directory/develop/msal-authentication-flows) |
0 commit comments