적용 대상: .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 인증을 구성 및 관리해야 합니다.
중요합니다
Microsoft.Data.SqlClient 7.0부터 Azure 및 Microsoft Entra ID 종속성은 더 이상 핵심 Microsoft.Data.SqlClient 패키지에 포함되지 않습니다. 라이브러리 또는 애플리케이션이 Microsoft Entra 인증 모드(예: Active Directory Default, Active Directory Managed IdentityActive Directory Interactive등)를 지원하는 경우 Microsoft.Data.SqlClient.Extensions.Azure NuGet 패키지에 대한 종속성을 포함해야 합니다. 마이그레이션 단계는 Microsoft.Data.SqlClient 7.0으로 마이그레이션을 참조하세요.
연결 문자열에서 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.Data.SqlClient 7.0.0부터 Microsoft Entra 인증 지원은 별도의
Microsoft.Data.SqlClient.Extensions.Azure패키지를 통해 제공됩니다. 핵심 드라이버 패키지는 더 이상 Azure 종속성을 전달하지 않습니다.
다음 섹션에서 설명하는 것 외에 Microsoft Entra 인증에 대한 자세한 내용은 Microsoft Entra 인증 사용을 참조하세요.
Microsoft Entra 인증 설정
애플리케이션이 Microsoft Entra 인증을 사용하여 Azure SQL 데이터 원본에 연결하는 경우 유효한 인증 모드를 제공해야 합니다. 다음 표에는 지원되는 인증 모드가 나열되어 있습니다. 애플리케이션은 연결 문자열에서 Authentication 연결 속성을 사용하여 모드를 지정합니다.
| 가치 | 설명 | Microsoft.Data.SqlClient 버전 |
|---|---|---|
| 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 이상 |
| Active Directory 암호 [사용되지 않음] | Microsoft Entra ID의 사용자 이름 및 암호를 사용하여 인증합니다. Active Directory 암호는 더 이상 사용되지 않습니다. 자세한 내용은 암호 인증 사용을 참조하세요. |
1.0 이상 |
1Microsoft.Data.SqlClient 2.0.0 이전에서 Active Directory Integrated 및 Active Directory Interactive 인증 모드는 .NET Framework에서만 지원됩니다.
통합 인증 사용
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를 사용한 인증을 Microsoft.Data.SqlClient v3.0 이상에서 보여 줍니다.
// 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 문서를 참조하세요.
중요합니다
Active Directory 기본값 은 서로 다른 환경 간의 연결 문자열 차이를 간소화하는 편리한 옵션입니다. 그러나 여러 위치에서 인증 정보를 찾아야 하기 때문에 성능에 영향을 미칠 수 있습니다. Active Directory 기본값을 사용하는 연결 속도가 느린 경우 환경에서 사용 중인 인증 방법을 구체적으로 대상으로 하는 다른 인증 옵션을 사용합니다. 엄격한 서비스 수준 응답 시간이 있는 환경에는 "Active Directory 기본값"이 권장되지 않습니다.
-
환경자격 증명
- 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부터 사용할 수 있습니다.
참고
InteractiveBrowserCredential 은 Active Directory 기본값의 드라이버 구현에서 사용할 수 없으며, Active Directory Interactive 는 MFA/대화형 인증을 사용하여 토큰을 획득하는 데 사용할 수 있는 유일한 옵션입니다.
현재 추가 사용자 지정 옵션을 사용할 수 없습니다.
다음 예제에서는 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를 사용한 인증을 Microsoft.Data.SqlClient v5.2 이후에서 보여 줍니다.
// 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();
}
암호 인증 사용 [사용되지 않음]
중요합니다
ActiveDirectoryPassword 인증 옵션(Microsoft Entra ID 암호 인증)은 Microsoft SQL 드라이버에서 더 이상 사용되지 않습니다. 이 고위험 인증 흐름은 필수 Microsoft Entra MFA(다단계 인증)와 호환되지 않으며 MFA가 적용되는 테넌트에서는 작동하지 않을 수 있습니다. 다른 Microsoft Entra 인증 방법으로 마이그레이션할 계획입니다.
Microsoft Entra ID 암호 인증은 OAuth 2.0 ROPC(리소스 소유자 암호 자격 증명) 부여를 기반으로 하며, 이를 통해 애플리케이션은 암호를 직접 처리하여 사용자에 로그인할 수 있습니다.
Microsoft MFA와 호환되지 않으므로 ROPC 흐름을 사용하지 않는 것이 좋습니다. 대부분의 시나리오에서는 보다 안전한 대안을 사용할 수 있으며 권장됩니다. 이 흐름은 애플리케이션에 대한 높은 수준의 신뢰가 필요하며 다른 흐름에 없는 위험을 수반합니다. 더 안전한 흐름이 실행 가능하지 않은 경우에만 이 흐름을 사용합니다. Microsoft는 악의적인 공격으로부터 사용자를 보호하기 위해 이 고위험 인증 흐름에서 벗어나고 있습니다. 자세한 내용은 Azure에 대한 필수 다단계 인증 계획을 참조하세요.
사용자가 로그인할 때 로그인한 사용자 및 조건부 액세스 정책에 대한 감사 내역 특성이 적용되도록 ActiveDirectoryInteractive 또는 ActiveDirectoryIntegrated 인증을 사용합니다.
무인 서비스 간 시나리오의 경우 Microsoft Entra 서비스 계정 지침을 따르세요:
- 애플리케이션이 Azure 인프라에서 실행되는 경우 ActiveDirectoryMSI(또는 일부 드라이버의 ActiveDirectoryManagedIdentity)를 사용합니다. 관리형 ID는 암호 및 인증서를 유지 관리하고 교체하는 데 따르는 오버헤드를 제거합니다.
- 관리 ID를 사용할 수 없는 경우(예: 애플리케이션이 Azure 외부에서 실행됨) ActiveDirectoryServicePrincipal을 사용합니다. 드라이버에서 지원하는 경우 클라이언트 암호보다 클라이언트 인증서를 선호합니다. 인증서를 사용하면 프라이빗 키가 클라이언트에 유지되고 서명된 어설션만 Microsoft Entra 전송되어 클라이언트를 인증합니다. 키가 하드웨어(예: TPM 또는 HSM)에 저장되거나 보고할 수 없는 것으로 표시된 경우 클라이언트 암호가 할 수 있는 방식으로 문자열로 복사할 수 없습니다.
- Microsoft Entra 사용자 계정을 서비스 계정으로 사용하지 마세요.
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();
}
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 CustomDeviceCodeFlowAuthProviderExample
{
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 Integrated, Active Directory Interactive, Active Directory Service Principal, Active Directory Device Code Flow, 및 Active Directory Password [사용되지 않음]이 포함됩니다.
애플리케이션 클라이언트 ID는 SqlAuthenticationProviderConfigurationSection 또는 SqlClientAuthenticationProviderConfigurationSection을 통해 구성할 수도 있습니다. 구성 속성 applicationClientId는 .NET Framework 4.6 이상 및 .NET Core 2.1 이상에 적용됩니다.
다음 코드 조각은 ActiveDirectoryAuthenticationProvider 인증이 사용 중일 때 사용자 정의 애플리케이션 클라이언트 ID와 함께 사용자 지정된 Active Directory Interactive 클래스를 사용하는 예제입니다.
using System;
using Microsoft.Data.SqlClient;
namespace ApplicationClientIdAzureAuthenticationProvider
{
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 사용
버전 5.2 이후로 제공되는 SqlConnection에 새로운 AccessTokenCallback 속성이 추가되었습니다. 들어오는 매개 변수가 주어졌을 때 액세스 토큰을 반환하는 사용자 지정 함수를 정의하려면 AccessTokenCallback 속성을 사용합니다. 연결 풀 내에서 액세스 토큰을 새로 고칠 수 있으므로 콜백을 사용하는 것이 AccessToken 속성을 사용하는 것보다 좋습니다.
AccessToken 속성을 사용하는 경우 연결을 연 후 토큰을 업데이트할 수 없습니다. 속성을 통해 제공된 연결된 만료일도 없습니다. 토큰이 만료되면 서버 인증 오류로 새 연결 요청이 실패하며, 이를 사용하는 풀을 수동으로 지워야 합니다.
중요합니다
동일한 AccessTokenCallback 입력 매개 변수에 대해 동일한 보안 컨텍스트의 액세스 토큰을 반환해야 합니다. 보안 컨텍스트가 다르면 잘못된 보안 컨텍스트를 가진 풀링된 연결이 연결 요청에 대해 반환될 수 있습니다.
참고
AccessTokenCallback 는 연결 풀을 식별하는 데 사용되는 키의 일부입니다. 매번 새 풀이 생성되므로 SqlConnection을 만들 때마다 새 함수 콜백을 만들지 마십시오. 풀링으로 간주하려는 연결에 대해 함수의 동일한 인스턴스를 참조합니다. 연결 풀 키에는 연결 풀을 적절하게 분할하기 위해 콜백에 전달된 매개 변수가 포함됩니다.
다음 코드 스니펫은 Microsoft에서 이 AccessTokenCallback 속성을 사용한 예시입니다. Data.SqlClient v5.2부터.
using System;
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 CustomDeviceCodeFlowAzureAuthenticationProviderExample
{
/// <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();
}
Microsoft.Data.SqlClient 7.0으로 마이그레이션
Microsoft.Data.SqlClient 7.0 은 핵심 패키지에서 Azure 및 Microsoft Entra ID 종속성을 새 확장 패키지로 추출하는 주요 릴리스입니다. 이 변경 내용은 SqlClient 리포지토리에서 가장 중요한 미해결 문제 였습니다. 다음 섹션에서는 변경된 내용과 애플리케이션을 업데이트하는 방법을 설명합니다.
7.0에서 변경된 내용
-
Azure 종속성 추출 - 핵심
Microsoft.Data.SqlClient패키지는 더 이상 전이적 종속성(예:Azure.Core및Azure.Identity)에 종속Microsoft.Identity.ClientMicrosoft.Web.WebView2되지 않습니다. 클래스 및 관련 형식이ActiveDirectoryAuthenticationProvider새Microsoft.Data.SqlClient.Extensions.Azure패키지로 이동되었습니다. -
새 패키지 — 이 분리를 지원하기 위해 두 개의 새 패키지가 도입되었습니다.
-
Microsoft.Data.SqlClient.Extensions.Azure— Entra ID 인증 지원을 포함합니다. -
Microsoft.Data.SqlClient.Extensions.Abstractions— 핵심 드라이버와 확장 간의 공유 형식입니다.
-
-
ActiveDirectoryPassword이제 사용 중단이SqlAuthenticationMethod.ActiveDirectoryPassword로 표시되어[Obsolete]컴파일러 경고를 발생시킵니다. 이는 필수 다단계 인증과 일치합니다. -
실행 가능한 오류 메시지 - 패키지를 설치하지 않고
Microsoft.Data.SqlClient.Extensions.AzureEntra ID 인증 방법을 사용하는 경우 드라이버는 올바른 패키지를 설치하도록 안내하는 실행 가능한 오류 메시지를 제공합니다.
1단계: Azure 확장 패키지 설치
애플리케이션에서 Microsoft Entra 인증 모드를 Microsoft.Data.SqlClient.Extensions.Azure 사용하는 경우 NuGet 패키지를 추가합니다.
dotnet add package Microsoft.Data.SqlClient.Extensions.Azure
또는 Visual Studio에서 NuGet 패키지 관리자를 사용하여 Microsoft.Data.SqlClient.Extensions.Azure 를 검색하여 설치합니다.
참고
패키지 참조를 추가하는 것 외에는 코드 변경이 필요하지 않습니다. 확장 패키지는 인증 공급자를 자동으로 등록합니다.
참고
애플리케이션이 Entra ID 인증 모드 자체를 구현하거나 토큰 기반 인증을 사용하여 Azure SQL에 연결하는 경우 Microsoft.Data.SqlClient.Extensions.Azure 패키지 참조를 포함할 필요가 없습니다. 이 패키지 참조는 엔트라 ID 인증 모드의 드라이버 제공 구현에만 필요합니다.
2단계: 사용되지 않는 인증 모드 바꾸기
Active Directory Password 인증은 더 이상 사용되지 않으며 7.0에서 컴파일러 경고를 생성합니다. 지원되는 대안으로 마이그레이션:
| 시나리오 | 권장 인증 모드 |
|---|---|
| 대화형/데스크톱 앱 | Active Directory Interactive |
| 서비스 간 통신 | Active Directory Service Principal |
| Azure 호스팅 워크로드 | Active Directory Managed Identity |
| 개발자/CI 환경 | Active Directory Default |
| Kubernetes/페더레이션된 워크로드 | Active Directory Workload Identity |
3단계: 연결 문자열 검토
모든 Authentication 연결 문자열 값은 동일한 방식으로 계속 작동합니다. 패키지가 설치되어 있는 한 Microsoft.Data.SqlClient.Extensions.Azure 마이그레이션에는 연결 문자열 변경이 필요하지 않습니다.
Entra ID 인증을 사용하지 않는 애플리케이션
애플리케이션이 SQL 인증, Windows 통합 인증을 사용하여 연결하는 경우 또는 AccessToken/AccessTokenCallback변경이 필요하지 않습니다. 종속성이 적은 더 가벼운 코어 패키지의 이점을 누릴 수 있습니다.