이미 Azure SQL Server를 구성하여 서버 관리자이고 내 계정에도 MFA를 사용하도록 설정했습니다. 이 문서 를 따르려고 했지만 MFA가있는 Active Directory에 대해서는 언급하지 않았습니다.
내 계정과 MFA를 사용하여 SQL Management Studio를 사용하여 서버에 로그인 할 수 있습니다.
처음에는 새 SqlAuthenticationMethod Enum 기반으로 시도했습니다 .
SqlConnection con = new SqlConnection("Server=tcp:myapp.database.windows.net;Database=CustomerDB;Authentication=Active Directory Interactive;Encrypt=True;[email protected]"))
오류:
''ActiveDirectoryInteractive '에 대한 인증 공급자를 찾을 수 없습니다.'
그런 다음 Azure 응용 프로그램을 통해 SQL에 액세스하는 방법에 대해 보았습니다. 그러나 이것은 제가 원하는 것이 아닙니다.
이 SO 질문 은 공급자없이 Driver
연결하고 연결 문자열에서 설정하는 방법 에 대해 설명합니다.
SqlConnection con = new SqlConnection("DRIVER={ODBC Driver 17 for SQL Server};Server=tcp:myapp.database.windows.net;Database=CustomerDB;Authentication=Active Directory Interactive;Encrypt=True;[email protected]"))
하지만 오류가 발생합니다.
'지원되지 않는 키워드 :'드라이버 '.'
어쨌든 연결을 시도 할 때 Microsoft 인증 상자가 팝업되어 다중 요소 인증을 통해 사용자를 안내하도록 연결 문자열을 작성할 수 있습니까?
Azure AD 인증을 사용하려면 C # 프로그램이 Azure AD 애플리케이션으로 등록해야합니다. 앱 등록을 완료하면 애플리케이션 ID가 생성되고 표시됩니다. 연결하려면 프로그램에이 ID가 포함되어야합니다. 애플리케이션에 필요한 권한을 등록하고 설정하려면 Azure Portal로 이동하여 Azure Active Directory> 앱 등록> 새 등록을 선택합니다.
앱 등록이 생성되면 애플리케이션 ID 값이 생성되어 표시됩니다.
API 권한> 권한 추가를 선택하십시오.
내 조직에서 사용하는 API를 선택하고> 검색에 Azure SQL Database를 입력하고> Azure SQL Database를 선택합니다.
위임 된 권한> user_impersonation> 권한 추가를 선택합니다.
Azure SQL Database에 대한 Azure AD 관리자를 이미 설정 한 것 같습니다.
SQL 사용자 생성 명령을 사용하여 데이터베이스에 사용자를 추가 할 수도 있습니다. 예를 들면 CREATE USER [] FROM EXTERNAL PROVIDER입니다. 자세한 내용은 여기를 참조 하십시오 .
아래는 C #의 예입니다.
using System;
// Reference to Azure AD authentication assembly
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using DA = System.Data;
using SC = System.Data.SqlClient;
using AD = Microsoft.IdentityModel.Clients.ActiveDirectory;
using TX = System.Text;
using TT = System.Threading.Tasks;
namespace ADInteractive5
{
class Program
{
// ASSIGN YOUR VALUES TO THESE STATIC FIELDS !!
static public string Az_SQLDB_svrName = "<Your SQL DB server>";
static public string AzureAD_UserID = "<Your User ID>";
static public string Initial_DatabaseName = "<Your Database>";
// Some scenarios do not need values for the following two fields:
static public readonly string ClientApplicationID = "<Your App ID>";
static public readonly Uri RedirectUri = new Uri("<Your URI>");
public static void Main(string[] args)
{
var provider = new ActiveDirectoryAuthProvider();
SC.SqlAuthenticationProvider.SetProvider(
SC.SqlAuthenticationMethod.ActiveDirectoryInteractive,
//SC.SqlAuthenticationMethod.ActiveDirectoryIntegrated, // Alternatives.
//SC.SqlAuthenticationMethod.ActiveDirectoryPassword,
provider);
Program.Connection();
}
public static void Connection()
{
SC.SqlConnectionStringBuilder builder = new SC.SqlConnectionStringBuilder();
// Program._ static values that you set earlier.
builder["Data Source"] = Program.Az_SQLDB_svrName;
builder.UserID = Program.AzureAD_UserID;
builder["Initial Catalog"] = Program.Initial_DatabaseName;
// This "Password" is not used with .ActiveDirectoryInteractive.
//builder["Password"] = "<YOUR PASSWORD HERE>";
builder["Connect Timeout"] = 15;
builder["TrustServerCertificate"] = true;
builder.Pooling = false;
// Assigned enum value must match the enum given to .SetProvider().
builder.Authentication = SC.SqlAuthenticationMethod.ActiveDirectoryInteractive;
SC.SqlConnection sqlConnection = new SC.SqlConnection(builder.ConnectionString);
SC.SqlCommand cmd = new SC.SqlCommand(
"SELECT '******** MY QUERY RAN SUCCESSFULLY!! ********';",
sqlConnection);
try
{
sqlConnection.Open();
if (sqlConnection.State == DA.ConnectionState.Open)
{
var rdr = cmd.ExecuteReader();
var msg = new TX.StringBuilder();
while (rdr.Read())
{
msg.AppendLine(rdr.GetString(0));
}
Console.WriteLine(msg.ToString());
Console.WriteLine(":Success");
}
else
{
Console.WriteLine(":Failed");
}
sqlConnection.Close();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Connection failed with the following exception...");
Console.WriteLine(ex.ToString());
Console.ResetColor();
}
}
} // EOClass Program.
/// <summary>
/// SqlAuthenticationProvider - Is a public class that defines 3 different Azure AD
/// authentication methods. The methods are supported in the new .NET 4.7.2.
/// .
/// 1. Interactive, 2. Integrated, 3. Password
/// .
/// All 3 authentication methods are based on the Azure
/// Active Directory Authentication Library (ADAL) managed library.
/// </summary>
public class ActiveDirectoryAuthProvider : SC.SqlAuthenticationProvider
{
// Program._ more static values that you set!
private readonly string _clientId = Program.ClientApplicationID;
private readonly Uri _redirectUri = Program.RedirectUri;
public override async TT.Task<SC.SqlAuthenticationToken>
AcquireTokenAsync(SC.SqlAuthenticationParameters parameters)
{
AD.AuthenticationContext authContext =
new AD.AuthenticationContext(parameters.Authority);
authContext.CorrelationId = parameters.ConnectionId;
AD.AuthenticationResult result;
switch (parameters.AuthenticationMethod)
{
case SC.SqlAuthenticationMethod.ActiveDirectoryInteractive:
Console.WriteLine("In method 'AcquireTokenAsync', case_0 == '.ActiveDirectoryInteractive'.");
result = await authContext.AcquireTokenAsync(
parameters.Resource, // "https://database.windows.net/"
_clientId,
_redirectUri,
new AD.PlatformParameters(AD.PromptBehavior.Auto),
new AD.UserIdentifier(
parameters.UserId,
AD.UserIdentifierType.RequiredDisplayableId));
break;
case SC.SqlAuthenticationMethod.ActiveDirectoryIntegrated:
Console.WriteLine("In method 'AcquireTokenAsync', case_1 == '.ActiveDirectoryIntegrated'.");
result = await authContext.AcquireTokenAsync(
parameters.Resource,
_clientId,
new AD.UserCredential());
break;
case SC.SqlAuthenticationMethod.ActiveDirectoryPassword:
Console.WriteLine("In method 'AcquireTokenAsync', case_2 == '.ActiveDirectoryPassword'.");
result = await authContext.AcquireTokenAsync(
parameters.Resource,
_clientId,
new AD.UserPasswordCredential(
parameters.UserId,
parameters.Password));
break;
default: throw new InvalidOperationException();
}
return new SC.SqlAuthenticationToken(result.AccessToken, result.ExpiresOn);
}
public override bool IsSupported(SC.SqlAuthenticationMethod authenticationMethod)
{
return authenticationMethod == SC.SqlAuthenticationMethod.ActiveDirectoryIntegrated
|| authenticationMethod == SC.SqlAuthenticationMethod.ActiveDirectoryInteractive
|| authenticationMethod == SC.SqlAuthenticationMethod.ActiveDirectoryPassword;
}
} // EOClass ActiveDirectoryAuthProvider.
} // EONamespace. End of entire program source code.
위의 예제는 Microsoft.IdentityModel.Clients.ActiveDirectory DLL 어셈블리를 사용합니다.
이 패키지를 설치하려면 Visual Studio에서 프로젝트> NuGet 패키지 관리를 선택합니다. Microsoft.IdentityModel.Clients.ActiveDirectory를 검색하여 설치합니다.
.NET Framework 버전 4.7.2부터 열거 형 SqlAuthenticationMethod에 ActiveDirectoryInteractive라는 새 값이 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다