如何从域外的.Net Project Test测试sql server连接windows身份验证

时间:2012-05-04 17:42:56

标签: c# .net sql-server ado.net

以下是cenario:

我在Active Directory上创建了一个名为测试的帐户。

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

我可以访问域内的数据>通过带有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身份验证模式。

2 个答案:

答案 0 :(得分:2)

如果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公开的端口

答案 1 :(得分:1)

当我在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}
}