如何从域外部的 .Net 项目测试测试 SQL 服务器连接窗口身份验证

本文关键字:测试 SQL 服务器 连接 身份验证 窗口 项目 Net 外部 | 更新日期: 2023-09-27 18:33:17

这是cenario:

我在活动目录上创建了一个名为Test的帐户。

此帐户具有读取数据库实例的权限。

我可以通过具有Windows身份验证的SQL Server Visual Management Studio访问域内的数据>。

现在的问题是:

如何在域外部>域将使用 .NET 项目测试访问此数据?

我把它放在我的app.config中:

<connectionStrings>
   <add name="CRM" connectionString="Data Source=server; Initial Catalog=catalog; Integrated Security=SSPI; providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
   <identity impersonate="true" userName="domain'user" password="pass"/>
</system.web>

但是我仍然收到此错误:

用户"x"登录失败。用户未与受信任的 SQL Server 连接关联。

最后也是最不重要的一点是,是的,我确实启用了SQL和Windows身份验证模式。

如何从域外部的 .Net 项目测试测试 SQL 服务器连接窗口身份验证

如果SQL服务器在域之外,那么你必须像这样提供服务器的IP和端口

连接字符串中的更改

<add name="CRM" connectionString="Data Source=server; Initial Catalog=catalog; Integrated Security=SSPI; providerName="System.Data.SqlClient"/>

<add name="CRM" connectionString="Data Source=212.22.231.11,1433; Initial Catalog=catalog; Integrated Security=SSPI; providerName="System.Data.SqlClient"/>

在上面的语句中,212.22.231.11 服务器在 SQL Server 中托管了数据库,而 1433 是 SQL Server 公开的端口

当我在AD域之外时,我使用以下代码片段:

using System.DirectoryServices;
using System.Diagnostics;
using System.Management;
using System.DirectoryServices.AccountManagement;
public bool IsAuthenticated(String domain, String username, String pwd)
{
    // this is a query of the students credentials
    try
    {
        //Bind to the native AdsObject to force authentication.                 
        String domainAndUsername = domain + "''" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
        Object obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();
        if (null == result)
        {
            return false;
        }
        //Update the new path to the user in the directory.
        _path = result.Path;
        _filterAttribute = (String)result.Properties["cn"][0];
    }
    catch (Exception ex){}
    return true;
}

然后我像这样使用它:

var adAuth = new LdapAuthentication(@"LDAP://snip.edu");            
bool auth = adAuth.IsAuthenticated("snip", "username","password"
if (auth)
{
    // do something}
}