C# 使用Active Directory Universal和MFA连接到Azure DB支持C中的身份验证#
我需要从c#控制台应用程序访问部分SQL表数据。我需要帮助从c#建立服务器连接 数据库详细信息:C# 使用Active Directory Universal和MFA连接到Azure DB支持C中的身份验证#,c#,azure,azure-active-directory,azure-sql-database,multi-factor-authentication,C#,Azure,Azure Active Directory,Azure Sql Database,Multi Factor Authentication,我需要从c#控制台应用程序访问部分SQL表数据。我需要帮助从c#建立服务器连接 数据库详细信息: Server type : Database Engine Authentication : Active Directory-Universal with MFA support. 另外,请务必让我知道如何提供连接属性?登录数据库有两种不同的情况 1) 用户使用其帐户登录,您可以使用该令牌对SQL数据库进行身份验证。在这种情况下,您可以使用标准的登录弹出窗口来为您处理MFA条目 2) 用户对
Server type : Database Engine
Authentication : Active Directory-Universal with MFA support.
另外,请务必让我知道如何提供连接属性?登录数据库有两种不同的情况 1) 用户使用其帐户登录,您可以使用该令牌对SQL数据库进行身份验证。在这种情况下,您可以使用标准的登录弹出窗口来为您处理MFA条目 2) 用户对数据库没有权限(大多数标准web应用就是一个例子),或者您正在创建需要登录数据库的自动服务。由于MFA的目的是让用户完成一些机器无法完成的操作,比如从手机输入代码,因此无人值守登录不适用于MFA 如果您处于第二种情况,则需要创建一个不受MFA保护的服务原则帐户,以便应用程序登录。应用程序将获得用于访问数据库的唯一appId和appSecret,而不是用户名和密码。您可以通过将机密放入密钥库并将该应用程序的访问权限限制为其运行所需的特定资源来添加额外的保护 请注意,在本例中,我们没有在连接字符串中传递用户名和密码。相反,我们在将令牌添加到连接之前单独获取令牌
string serverName = "myserver.database.windows.net";
string databaseName = "test";
string clientId = "xxxxxx-xxxxx-xxxxx-xxxx-xxxx";
string aadTenantId = "xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxxx";
string clientSecretKey = "xxxxx/xxxxxx/xxxxx";
string sqlConnectionString = String.Format("Data Source=tcp:{0},1433;Initial Catalog={1};Persist Security Info=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False", serverName, databaseName);
string AadInstance = "https://login.windows.net/{0}";
string ResourceId = "https://database.windows.net/";
AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(AadInstance, aadTenantId));
ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
DateTime startTime = DateTime.Now;
Console.WriteLine("Time " + String.Format("{0:mm:ss.fff}", startTime));
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(ResourceId, clientCredential).Result;
DateTime endTime = DateTime.Now;
Console.WriteLine("Got token at " + String.Format("{0:mm:ss.fff}", endTime));
Console.WriteLine("Total time to get token in milliseconds " + (endTime - startTime).TotalMilliseconds);
using (var conn = new SqlConnection(sqlConnectionString))
{
conn.AccessToken = authenticationResult.AccessToken;
//DO STUFF
}
如果您不想摆弄令牌或将您的C#应用程序注册为Azure应用程序,您可以使用ODBC或OLE DB,它可以使用MFA/ActiveDirectoryInteractive身份验证: ODBC: OLE DB:
using System.Data.OleDb;
...
OleDbConnection con = new OleDbConnection("Provider=MSOLEDBSQL;Data Source=sqlserver.database.windows.net;User ID=user@domain.com;Initial Catalog=database;Authentication=ActiveDirectoryInteractive");
该应用程序将如何使用?最重要的是,您需要无人参与的登录吗?如果需要,服务原则登录是一种选择吗?
using System.Data.OleDb;
...
OleDbConnection con = new OleDbConnection("Provider=MSOLEDBSQL;Data Source=sqlserver.database.windows.net;User ID=user@domain.com;Initial Catalog=database;Authentication=ActiveDirectoryInteractive");