적용 대상: .NET Framework
.NET
.NET Standard
이 문서에서는 SqlClient로 .NET 애플리케이션에서 Microsoft Entra 인증을 사용하여 Azure SQL 데이터 원본에 연결하는 방법을 설명합니다.
참고
Microsoft Entra ID는 Azure AD(Azure Active Directory)의 새 이름이지만, 기존 환경의 중단을 방지하기 위해 UI 필드, 연결 공급자, 오류 코드 및 cmdlet과 같은 일부 하드 코딩된 요소에는 여전히 Azure AD가 남아 있습니다. 이 문서에서는 두 이름을 서로 바꾸어 쓸 수 있습니다.
개요
Microsoft Entra 인증은 Microsoft Entra ID의 ID를 사용하여 Azure SQL 데이터베이스, Azure SQL Managed Instance 및 Azure Synapse Analytics와 같은 데이터 원본에 액세스합니다. Microsoft.Data.SqlClient 네임스페이스를 사용하면 클라이언트 애플리케이션이 Azure SQL 데이터베이스 및 Azure SQL Managed Instance에 연결할 때 다양한 인증 모드에서 Microsoft Entra 자격 증명을 지정할 수 있습니다. Azure SQL로 Microsoft Entra 인증을 사용하려면 Azure SQL로 Microsoft Entra 인증을 구성 및 관리해야 합니다.
연결 문자열에서 Authentication
연결 속성을 설정하면 클라이언트는 제공된 값에 따라 기본 Microsoft Entra 인증 모드를 선택할 수 있습니다.
초기 Microsoft.Data.SqlClient 버전은 .NET Framework, .NET Core 및 .NET Standard에 대한
Active Directory Password
를 지원합니다. .NET Framework에 대한Active Directory Integrated
인증 및Active Directory Interactive
인증도 지원합니다.Microsoft.Data.SqlClient 2.0.0부터
Active Directory Integrated
인증 및Active Directory Interactive
인증에 대한 지원이 .NET Framework, .NET Core 및 .NET Standard로 확장됩니다.새
Active Directory Service Principal
인증 모드도 SqlClient 2.0.0에 추가되었습니다. 인증을 수행하기 위해 서비스 주체 ID의 클라이언트 ID와 암호를 사용합니다.Microsoft.Data.SqlClient 2.1.0에는
Active Directory Device Code Flow
및Active Directory Managed Identity
(Active Directory MSI
라고도 함) 등 더 많은 인증 모드가 추가됩니다. 이러한 새로운 모드를 사용하면 애플리케이션이 서버에 연결하기 위한 액세스 토큰을 획득할 수 있습니다.
다음 섹션에서 설명하는 것 외에 Microsoft Entra 인증에 대한 자세한 내용은 Microsoft Entra 인증 사용을 참조하세요.
Microsoft Entra 인증 설정
애플리케이션이 Microsoft Entra 인증을 사용하여 Azure SQL 데이터 원본에 연결하는 경우 유효한 인증 모드를 제공해야 합니다. 다음 표에는 지원되는 인증 모드가 나열되어 있습니다. 애플리케이션은 연결 문자열에서 Authentication
연결 속성을 사용하여 모드를 지정합니다.
가치 | 설명 | Microsoft.Data.SqlClient 버전 |
---|---|---|
Active Directory 암호 | Microsoft Entra ID의 사용자 이름 및 비밀번호로 인증 | 1.0 이상 |
Active Directory 통합 | IWA(Windows 통합 인증)를 사용하여 Microsoft Entra ID로 인증 | 2.0.0 이상1 |
Active Directory 대화형 | 대화형 인증을 사용하여 Microsoft Entra ID로 인증 | 2.0.0 이상1 |
Active Directory 서비스 주체 | 클라이언트 ID 및 비밀을 사용하여 Microsoft Entra 서비스 주체로 인증 | 2.0.0 이상 |
Active Directory 디바이스 코드 흐름 | Device Code Flow 모드를 사용하여 Microsoft Entra ID로 인증 | 2.1.0 이상 |
Active Directory 관리된 아이디 액티브 디렉터리 MSI |
Microsoft Entra 시스템이 할당한 관리 ID 또는 사용자가 할당한 관리 ID를 사용하여 인증합니다. | 2.1.0 이상 |
Active Directory 기본값 | 관리 ID, Visual Studio Code, Visual Studio, Azure CLI 등을 비롯한 암호 없는 비대화형 메커니즘을 사용하여 Microsoft Entra ID로 인증합니다. | 3.0.0 이상 |
Active Directory 워크로드 ID | 워크로드 ID에 대한 지원을 사용하도록 설정한 Azure 클라이언트 환경에서 SQL Database에 연결하기 위해 페더레이션된 사용자가 할당한 관리 ID를 사용하여 Microsoft Entra ID로 인증합니다. | 5.2.0 이상 |
1Microsoft.Data.SqlClient 2.0.0 이전에서 Active Directory Integrated
및 Active Directory Interactive
인증 모드는 .NET Framework에서만 지원됩니다.
암호 인증 사용
Active Directory Password
인증 모드는 네이티브 또는 페더레이션된 Microsoft Entra 사용자에 대해 Microsoft Entra ID를 사용하여 Azure 데이터 원본에 대한 인증을 지원합니다. 이 모드를 사용하는 경우 연결 문자열에 사용자 자격 증명을 제공해야 합니다. 다음 예제에서는 Active Directory Password
인증을 사용하는 방법을 보여줍니다.
// Use your own server, database, user ID, and password.
string ConnectionString = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Password; Encrypt=True; Database=testdb;"
+ "User Id=user@domain.com; Password=<password>";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
}
통합 인증 사용
Active Directory Integrated
인증 모드를 사용하려면 클라우드의 Microsoft Entra ID에 조인된 온-프레미스 Active Directory 인스턴스가 있어야 합니다. 예를 들어 AD FS(Active Directory Federation Services)를 사용하여 페더레이션할 수 있습니다.
도메인 조인된 컴퓨터에 로그인한 경우 이 모드를 사용하면 자격 증명을 묻는 메시지가 표시되지 않고 Azure SQL 데이터 원본에 액세스할 수 있습니다. .NET Framework 애플리케이션의 연결 문자열에는 사용자 이름 및 비밀번호를 지정할 수 없습니다. 사용자 이름은 .NET Core 및 .NET Standard 애플리케이션의 연결 문자열에서 선택 사항입니다. 이 모드에서는 SqlConnection의 Credential
속성을 설정할 수 없습니다.
다음 코드 조각은 Active Directory Integrated
인증이 사용 중인 경우의 예입니다.
// Use your own server and database.
string ConnectionString1 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Integrated; Encrypt=True; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString1)) {
conn.Open();
}
// User ID is optional for .NET Core and .NET Standard.
string ConnectionString2 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Integrated; Encrypt=True; Database=testdb;"
+ "User Id=user@domain.com";
using (SqlConnection conn = new SqlConnection(ConnectionString2)) {
conn.Open();
}
대화형 인증 사용
Active Directory Interactive
인증은 Azure SQL 데이터 원본에 연결하기 위한 다단계 인증 기술을 지원합니다. 연결 문자열에 이 인증 모드를 제공하면 Azure 인증 화면이 나타나고 사용자에게 유효한 자격 증명을 입력하도록 요청합니다. 연결 문자열에 암호를 지정할 수 없습니다.
이 모드에서는 SqlConnection의 Credential
속성을 설정할 수 없습니다.
Microsoft.Data.SqlClient 2.0.0 이상 버전에서는 대화형 모드인 경우 연결 문자열에 사용자 이름을 사용할 수 있습니다.
다음 예제에서는 Active Directory Interactive
인증을 사용하는 방법을 보여줍니다.
// Use your own server, database, and user ID.
// User ID is optional.
string ConnectionString1 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Interactive; Encrypt=True;"
+ "Database=testdb; User Id=user@domain.com";
using (SqlConnection conn = new SqlConnection(ConnectionString1)) {
conn.Open();
}
// User ID is not provided.
string ConnectionString2 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Interactive; Encrypt=True;"
+ "Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString2)) {
conn.Open();
}
서비스 주체 인증 사용
Active Directory Service Principal
인증 모드에서 클라이언트 애플리케이션은 서비스 주체 ID의 클라이언트 ID 및 비밀을 제공하여 Azure SQL 데이터 원본에 연결할 수 있습니다. 서비스 주체 인증에는 다음이 포함됩니다.
- 비밀을 사용하여 앱 등록 설정.
- Azure SQL Database 인스턴스의 앱에 대한 권한 부여.
- 올바른 자격 증명을 사용하여 연결.
다음 예제에서는 Active Directory Service Principal
인증을 사용하는 방법을 보여줍니다.
// Use your own server, database, app ID, and secret.
string ConnectionString = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Service Principal; Encrypt=True;"
+ "Database=testdb; User Id=AppId; Password=<password>";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
}
디바이스 코드 흐름 인증 사용
.NET(MSAL.NET)용 Microsoft 인증 라이브러리를 사용하면 Active Directory Device Code Flow
인증을 통해 클라이언트 애플리케이션이 대화형 웹 브라우저가 없는 디바이스 및 운영 체제에서 Azure SQL 데이터 원본에 연결할 수 있습니다. 대화형 인증은 다른 디바이스에서 수행됩니다. 디바이스 코드 흐름 인증에 대한 자세한 내용은 OAuth 2.0 디바이스 코드 흐름을 참조하세요.
이 모드를 사용 중인 경우 Credential
의 SqlConnection
속성을 설정할 수 없습니다. 또한 연결 문자열에 사용자 이름과 암호를 지정하면 안 됩니다.
다음 코드 조각은 Active Directory Device Code Flow
인증을 사용하는 예입니다.
참고
Active Directory Device Code Flow
의 시간 제한 기본값은 연결의 Connect Timeout
설정입니다. 디바이스 코드 흐름 인증 프로세스를 진행하는 데 충분한 시간을 제공하는 Connect Timeout
을 지정해야 합니다.
// Use your own server and database and increase Connect Timeout as needed for
// device code flow.
string ConnectionString = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Device Code Flow; Encrypt=True;"
+ "Database=testdb; Connect Timeout=180;";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
}
관리 ID 인증 사용
Azure 리소스에 대한 관리 ID로 인증은 SQL에 대한 프로그래밍 방식 액세스에 권장되는 인증 방법입니다. 클라이언트 애플리케이션은 ID를 제공하고 이를 사용하여 액세스 토큰을 가져오는 방식으로 리소스의 시스템이 할당한 관리 ID 또는 사용자가 할당한 관리 ID를 사용하여 Microsoft Entra ID로 SQL에 인증할 수 있습니다. 이 방법을 사용하면 자격 증명 및 비밀을 관리할 필요가 없으며 액세스 관리를 간소화할 수 있습니다.
두 가지 종류의 관리 ID가 있습니다.
- 시스템이 할당한 관리 ID는 Azure 리소스(예: SQL 관리형 인스턴스 또는 논리 서버)의 일부로 생성되며 해당 리소스의 수명 주기를 공유합니다. 시스템 할당 ID는 하나의 Azure 리소스에만 연결할 수 있습니다.
- 사용자가 할당한 관리 ID는 독립 실행형 Azure 리소스로 생성됩니다. 하나 이상의 Azure 서비스에 할당할 수 있습니다.
관리 ID에 대한 자세한 내용은 Azure 리소스에 대한 관리 ID 정보를 참조하세요.
Microsoft.Data.SqlClient 2.1.0부터 드라이버는 관리 ID를 통해 액세스 토큰을 획득하여 Azure SQL 데이터베이스, Azure Synapse Analytics 및 Azure SQL Managed Instance에 대한 인증을 지원합니다. 이 인증을 사용하려면 연결 문자열에서 Active Directory Managed Identity
또는 Active Directory MSI
를 지정합니다. 비밀번호는 필요하지 않습니다. 이 모드에서는 Credential
의 SqlConnection
속성을 설정할 수 없습니다.
사용자가 할당한 관리 ID의 경우 Microsoft.Data.SqlClient v3.0 이상을 사용할 때 관리 ID의 클라이언트 ID를 제공해야 합니다. Microsoft.Data.SqlClient v2.1을 사용하는 경우 관리 ID의 개체 ID를 제공해야 합니다.
다음 예제에서는 시스템이 할당한 관리 ID로 Active Directory Managed Identity
인증을 사용하는 방법을 보여줍니다.
// For system-assigned managed identity
// Use your own values for Server and Database.
string ConnectionString1 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Managed Identity; Encrypt=True;"
+ "Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString1)) {
conn.Open();
}
string ConnectionString2 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory MSI; Encrypt=True; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString2)) {
conn.Open();
}
다음 예제에서는 Active Directory Managed Identity
에서 사용자가 할당한 관리 ID를 사용한 인증을 보여 줍니다.
// For user-assigned managed identity
// Use your own values for Server, Database, and User Id.
// With Microsoft.Data.SqlClient v3.0+
string ConnectionString1 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Managed Identity; Encrypt=True;"
+ "User Id=ClientIdOfManagedIdentity; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString1)) {
conn.Open();
}
// With Microsoft.Data.SqlClient v3.0+
string ConnectionString2 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory MSI; Encrypt=True;"
+ "User Id=ClientIdOfManagedIdentity; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString2)) {
conn.Open();
}
다음 예제에서는 Active Directory Managed Identity
에서 사용자가 할당한 관리 ID를 사용한 인증을 보여 줍니다.
// For user-assigned managed identity
// Use your own values for Server, Database, and User Id.
// With Microsoft.Data.SqlClient v2.1
string ConnectionString1 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Managed Identity; Encrypt=True;"
+ "User Id=ObjectIdOfManagedIdentity; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString1)) {
conn.Open();
}
// With Microsoft.Data.SqlClient v2.1
string ConnectionString2 = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory MSI; Encrypt=True;"
+ "User Id=ObjectIdOfManagedIdentity; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString2)) {
conn.Open();
}
기본 인증 사용
버전 3.0부터 사용할 수 있는 이 인증 모드는 사용자 인증의 가능성을 확대합니다. 이 모드는 로그인 솔루션을 클라이언트 환경, Visual Studio Code, Visual Studio, Azure CLI 등으로 확장합니다.
이 인증 모드에서 드라이버는 액세스 토큰을 획득하기 위해 Azure ID 라이브러리에서 “DefaultAzureCredential”을 전달하여 토큰을 획득합니다. 이 모드는 자격 증명 형식 집합을 사용하여 액세스 토큰을 순서대로 획득하려고 시도합니다. 사용된 Azure ID 라이브러리의 버전에 따라 자격 증명 집합이 달라집니다. 버전별 차이점은 목록에 나와 있습니다. Azure ID 버전별 동작은 Azure.Identity API 문서를 참조하세요.
-
환경자격 증명
- Microsoft Entra ID에 대한 인증을 클라이언트와 비밀, 또는 사용자 이름과 암호를 사용하여 다음 환경 변수에 구성된 세부 정보로 활성화합니다: AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_CLIENT_CERTIFICATE_PATH, AZURE_USERNAME, AZURE_PASSWORD (자세한 정보).
-
WorkloadIdentity자격 증명
- Kubernetes 및 워크로드 ID를 지원하는 다른 호스트에서 Microsoft Entra 워크로드 ID 인증을 사용하도록 설정합니다. 자세한 내용은 Microsoft Entra 워크로드 ID를 참조하세요. Azure ID 버전 1.10 및 Microsoft.Data.SqlClient 5.1.4부터 사용할 수 있습니다.
-
ManagedIdentity자격 증명
- 배포 환경에 할당된 관리 ID를 사용하여 Microsoft Entra ID로 인증을 시도합니다. “사용자가 할당한 관리 ID”의 “클라이언트 ID”는 “사용자 ID” 연결 속성에서 읽습니다.
-
SharedTokenCache자격 증명
- Microsoft 애플리케이션 간에 공유되는 로컬 캐시에서 토큰을 사용하여 인증합니다.
-
VisualStudio자격 증명
- Visual Studio의 데이터를 사용하여 Microsoft Entra ID로 인증을 사용하도록 설정합니다.
-
VisualStudioCode자격 증명
- Visual Studio Code의 데이터를 사용하여 Microsoft Entra ID로 인증을 사용하도록 설정합니다.
-
AzurePowerShell자격 증명
- Azure PowerShell을 사용하여 Microsoft Entra ID로 인증을 사용하도록 설정합니다. Azure ID 버전 1.6 및 Microsoft.Data.SqlClient 5.0부터 사용할 수 있습니다.
-
AzureCliCredential
- 액세스 토큰을 가져오기 위해 Azure CLI를 사용하여 Microsoft Entra ID로 인증을 사용하도록 설정합니다.
-
AzureDeveloperCli자격 증명
- 액세스 토큰을 가져오기 위해 Azure Developer CLI를 사용하여 Microsoft Entra ID에 대한 인증을 사용하도록 설정합니다. Azure ID 버전 1.10 및 Microsoft.Data.SqlClient 5.1.4부터 사용할 수 있습니다.
참고
"Active Directory Default"의 드라이버 구현에서 InteractiveBrowserCredential은 사용되지 않으며 MFA/대화형 인증을 사용하여 토큰을 획득하는 데 사용할 수 있는 유일한 옵션은 "Active Directory Interactive"입니다.
현재 추가 사용자 지정 옵션은 사용할 수 없습니다.
다음 예제에서는 Active Directory Default 인증을 사용하는 방법을 보여줍니다.
// Use your own server, database
string ConnectionString = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Default; Encrypt=True; Database=testdb;";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
}
워크로드 ID 인증 사용
관리 ID와 같이 버전 5.2부터 사용할 수 있는 워크로드 ID 인증 모드는 지정된 경우 클라이언트 ID의 연결 문자열에 User ID
매개 변수의 값을 사용합니다. 그러나 관리 ID와 달리 WorkloadIdentityCredentialOptions는 환경 변수인 AZURE_TENANT_ID, AZURE_CLIENT_ID 및 AZURE_FEDERATED_TOKEN_FILE의 값을 기본값으로 사용합니다. 그러나 클라이언트 ID만 연결 문자열로 재정의할 수 있습니다.
다음 예제에서는 Active Directory Workload Identity
에서 사용자가 할당한 관리 ID를 사용한 인증을 보여 줍니다.
// Use your own values for Server, Database, and User Id.
// With Microsoft.Data.SqlClient v5.2+
string ConnectionString = @"Server=demo.database.windows.net;"
+ "Authentication=Active Directory Workload Identity; Encrypt=True;"
+ "User Id=ClientIdOfManagedIdentity; Database=testdb";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
}
Microsoft Entra 인증을 사용자 지정하기
드라이버에 기본 제공되는 Microsoft Entra 인증을 사용하는 것 외에도 Microsoft.Data.SqlClient 2.1.0 이상 버전에서는 애플리케이션에 Microsoft Entra 인증을 사용자 지정할 수 있는 옵션을 제공합니다. 사용자 지정은 ActiveDirectoryAuthenticationProvider
추상 클래스에서 파생된 SqlAuthenticationProvider
클래스를 기반으로 합니다.
Microsoft Entra 인증 중에 클라이언트 애플리케이션은 다음 중 하나를 통해 자체 ActiveDirectoryAuthenticationProvider
클래스를 정의할 수 있습니다.
- 사용자 지정된 콜백 메서드를 사용합니다.
- 액세스 토큰을 가져오기 위해 SqlClient 드라이버를 통해 MSAL 라이브러리에 애플리케이션 클라이언트 ID를 전달합니다.
다음 예제에서는 Active Directory Device Code Flow
인증이 사용 중일 때 사용자 지정 콜백을 사용하는 방법을 보여줍니다.
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Data.SqlClient;
namespace CustomAuthenticationProviderExamples
{
public class Program
{
public static void Main()
{
SqlAuthenticationProvider authProvider = new ActiveDirectoryAuthenticationProvider(CustomDeviceFlowCallback);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, authProvider);
using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Device Code Flow;Database=<db>;"))
{
sqlConnection.Open();
Console.WriteLine("Connected successfully!");
}
}
private static Task CustomDeviceFlowCallback(DeviceCodeResult result)
{
// Provide custom logic to process result information and read device code.
Console.WriteLine(result.Message);
return Task.FromResult(0);
}
}
}
사용자 지정된 ActiveDirectoryAuthenticationProvider
클래스를 사용하면 지원되는 Microsoft Entra 인증 모드가 사용 중일 때 사용자 정의 애플리케이션 클라이언트 ID를 SqlClient에 전달할 수 있습니다. 지원되는 Microsoft Entra 인증 모드에는 Active Directory Password
, Active Directory Integrated
, Active Directory Interactive
, Active Directory Service Principal
, Active Directory Device Code Flow
가 있습니다.
애플리케이션 클라이언트 ID는 SqlAuthenticationProviderConfigurationSection
또는 SqlClientAuthenticationProviderConfigurationSection
을 통해 구성할 수도 있습니다. 구성 속성 applicationClientId
는 .NET Framework 4.6 이상 및 .NET Core 2.1 이상에 적용됩니다.
다음 코드 조각은 ActiveDirectoryAuthenticationProvider
인증이 사용 중일 때 사용자 정의 애플리케이션 클라이언트 ID와 함께 사용자 지정된 Active Directory Interactive
클래스를 사용하는 예제입니다.
using System;
using Microsoft.Data.SqlClient;
namespace CustomAuthenticationProviderExamples
{
public class Program
{
public static void Main()
{
// Supported for all authentication modes supported by ActiveDirectoryAuthenticationProvider
ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider("<application_client_id>");
if (provider.IsSupported(SqlAuthenticationMethod.ActiveDirectoryInteractive))
{
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
}
using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Interactive;Database=<db>;"))
{
sqlConnection.Open();
Console.WriteLine("Connected successfully!");
}
}
}
}
다음 예제에서는 구성 섹션을 통해 애플리케이션 클라이언트 ID를 설정하는 방법을 보여줍니다.
<configuration>
<configSections>
<section name="SqlClientAuthenticationProviders"
type="Microsoft.Data.SqlClient.SqlClientAuthenticationProviderConfigurationSection, Microsoft.Data.SqlClient" />
</configSections>
<SqlClientAuthenticationProviders applicationClientId ="<GUID>" />
</configuration>
<!--or-->
<configuration>
<configSections>
<section name="SqlAuthenticationProviders"
type="Microsoft.Data.SqlClient.SqlAuthenticationProviderConfigurationSection, Microsoft.Data.SqlClient" />
</configSections>
<SqlAuthenticationProviders applicationClientId ="<GUID>" />
</configuration>
AccessTokenCallback 사용
SqlConnection에는 버전 5.2 이상에서 사용 가능한 새 AccessTokenCallback 속성이 있습니다. 들어오는 매개 변수가 주어졌을 때 액세스 토큰을 반환하는 사용자 지정 함수를 정의하려면 AccessTokenCallback
속성을 사용합니다. 연결 풀 내에서 액세스 토큰을 새로 고칠 수 있으므로 콜백을 사용하는 것이 AccessToken 속성을 사용하는 것보다 좋습니다.
AccessToken
속성을 사용하는 경우 연결을 연 후 토큰을 업데이트할 수 없습니다. 속성을 통해 제공된 연결된 만료일도 없습니다. 토큰이 만료되면 서버 인증 오류로 새 연결 요청이 실패하며, 이를 사용하는 풀을 수동으로 지워야 합니다.
중요합니다
동일한 AccessTokenCallback
입력 매개 변수에 대해 동일한 보안 컨텍스트의 액세스 토큰을 반환해야 합니다. 보안 컨텍스트가 다르면 잘못된 보안 컨텍스트를 가진 풀링된 연결이 연결 요청에 대해 반환될 수 있습니다.
참고
AccessTokenCallback
는 연결 풀을 식별하는 데 사용되는 키의 일부입니다. 매번 새 풀이 생성되므로 SqlConnection을 만들 때마다 새 함수 콜백을 만들지 마십시오. 풀링으로 간주하려는 연결에 대해 함수의 동일한 인스턴스를 참조합니다. 연결 풀 키에는 연결 풀을 적절하게 분할하기 위해 콜백에 전달된 매개 변수가 포함됩니다.
다음 코드 조각은 AccessTokenCallback
에서 속성을 사용하는 예제입니다.
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
OpenSqlConnection();
Console.ReadLine();
}
const string defaultScopeSuffix = "/.default";
// Reuse credential objects to take advantage of underlying token caches
private static ConcurrentDictionary<string, DefaultAzureCredential> credentials = new ConcurrentDictionary<string, DefaultAzureCredential>();
// Use a shared callback function for connections that should be in the same connection pool
private static Func<SqlAuthenticationParameters, CancellationToken, Task<SqlAuthenticationToken>> myAccessTokenCallback =
async (authParams, cancellationToken) =>
{
string scope = authParams.Resource.EndsWith(defaultScopeSuffix)
? authParams.Resource
: $"{authParams.Resource}{defaultScopeSuffix}";
DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions();
options.ManagedIdentityClientId = authParams.UserId;
// Reuse the same credential object if we are using the same MI Client Id
AccessToken token = await credentials.GetOrAdd(authParams.UserId, new DefaultAzureCredential(options)).GetTokenAsync(
new TokenRequestContext(new string[] { scope }),
cancellationToken);
return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
};
private static void OpenSqlConnection()
{
// (Optional) Pass a User-Assigned Managed Identity Client ID.
// This will ensure different MI Client IDs are in different connection pools.
string connectionString = "Server=myServer.database.windows.net;Encrypt=Mandatory;UserId=<ManagedIdentitityClientId>;";
using (SqlConnection connection = new SqlConnection(connectionString)
{
// The callback function is part of the connection pool key. Using a static callback function
// ensures connections will not create a new pool per connection just for the callback.
AccessTokenCallback = myAccessTokenCallback
})
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
}
사용자 지정 SQL 인증 공급자 지원
더 많은 유연성을 위해 클라이언트 애플리케이션은 Microsoft Entra 인증에 ActiveDirectoryAuthenticationProvider
클래스를 사용하는 대신 자체 공급자를 사용할 수도 있습니다. 사용자 지정 인증 공급자는 재정의된 메서드가 있는 SqlAuthenticationProvider
의 하위 클래스여야 합니다. 그런 다음 사용자 지정 공급자를 등록하고 기존 Active Directory*
인증 방법 중 하나 이상을 재정의해야 합니다.
중요합니다
인증 공급자는 동일한 입력 매개 변수에 대해 동일한 보안 컨텍스트의 액세스 토큰을 반환해야 합니다. 보안 컨텍스트가 다르면 잘못된 보안 컨텍스트를 가진 풀링된 연결이 연결 요청에 대해 반환될 수 있습니다.
다음 예제에서는 Active Directory Device Code Flow
인증에 새 인증 공급자를 사용하는 방법을 보여줍니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.Identity.Client;
namespace CustomAuthenticationProviderExamples
{
/// <summary>
/// Example demonstrating creating a custom device code flow authentication provider and attaching it to the driver.
/// This is helpful for applications that wish to override the Callback for the Device Code Result implemented by the SqlClient driver.
/// </summary>
public class CustomDeviceCodeFlowAzureAuthenticationProvider : SqlAuthenticationProvider
{
private const string ClientId = "my-client-id";
private const string ClientName = "My Application Name";
private const string DefaultScopeSuffix = "/.default";
// Maintain a copy of the PublicClientApplication object to cache the underlying access tokens it provides
private static IPublicClientApplication pcApplication;
public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters)
{
string[] scopes = [ parameters.Resource.EndsWith(DefaultScopeSuffix) ? parameters.Resource : parameters.Resource + DefaultScopeSuffix ];
IPublicClientApplication app = pcApplication;
if (app == null)
{
pcApplication = app = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(parameters.Authority)
.WithClientName(ClientName)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.Build();
}
AuthenticationResult result;
using CancellationTokenSource connectionTimeoutCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(parameters.ConnectionTimeout));
try
{
IEnumerable<IAccount> accounts = await app.GetAccountsAsync();
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync(connectionTimeoutCancellation.Token);
}
catch (MsalUiRequiredException)
{
result = await app.AcquireTokenWithDeviceCode(scopes, deviceCodeResult => CustomDeviceFlowCallback(deviceCodeResult))
.ExecuteAsync(connectionTimeoutCancellation.Token);
}
return new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn);
}
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
=> authenticationMethod.Equals(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow);
private static Task CustomDeviceFlowCallback(DeviceCodeResult result)
{
Console.WriteLine(result.Message);
return Task.CompletedTask;
}
}
public class Program
{
public static void Main()
{
// Register our custom authentication provider class to override Active Directory Device Code Flow
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, new CustomDeviceCodeFlowAzureAuthenticationProvider());
using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Device Code Flow;Database=<db>;"))
{
sqlConnection.Open();
Console.WriteLine("Connected successfully!");
}
}
}
}
Active Directory Interactive
인증 환경을 개선하는 것 외에도, Microsoft.Data.SqlClient 2.1.0 이상 버전에서는 대화형 인증 및 디바이스 코드 흐름 인증을 사용자 지정하기 위해 클라이언트 애플리케이션에 대해 다음 API를 제공합니다.
public class ActiveDirectoryAuthenticationProvider
{
// For .NET Framework targeted applications only
// Sets a reference to the current System.Windows.Forms.IWin32Window that triggers
// the browser to be shown.
// Used to center the browser pop-up onto this window.
public void SetIWin32WindowFunc(Func<IWin32Window> iWin32WindowFunc);
// For .NET Standard targeted applications only
// Sets a reference to the ViewController (if using .NET for iOS), Activity
// (if using .NET for Android) IWin32Window, or IntPtr (if using .NET Framework).
// Used for invoking the browser for Active Directory Interactive authentication.
public void SetParentActivityOrWindowFunc(Func<object> parentActivityOrWindowFunc);
// For .NET Framework, .NET Core, and .NET Standard targeted applications
// Sets a callback method that's invoked with a custom web UI instance that lets
// the user sign in with Azure AD, present consent if needed, and get back the
// authorization code.
// Applicable when working with Active Directory Interactive authentication.
public void SetAcquireAuthorizationCodeAsyncCallback(Func<Uri, Uri, CancellationToken,
Task<Uri>> acquireAuthorizationCodeAsyncCallback);
// For .NET Framework, .NET Core, and .NET Standard targeted applications
// Clears cached user tokens from the token provider.
public static void ClearUserTokenCache();
}