我遵循tutorial在ASP.NET/C#4.0 Web應用程序上實現LDAP身份驗證。雖然事情似乎有效,但當我將該網站置於IIS7下時,它無法獲取組名。LDAP - 獲取用戶的組名失敗IIS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Collections;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
namespace KEWeb
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
private string _username;
private string _password;
private string _domain;
private string _domainAndUsername;
private DirectoryEntry _entry;
private DirectorySearcher _search;
private SearchResult _result;
public LdapAuthentication(string path, string domain, string username, string password)
{
_path = path;
_domain = domain;
_username = username;
_password = password;
_domainAndUsername = _domain + @"\" + _username;
_entry = new DirectoryEntry(_path, _domainAndUsername, _password);
}
public bool IsAuthenticated()
{
try
{
Object obj = _entry.NativeObject;
_search = new DirectorySearcher(_entry);
_search.Filter = "(SAMAccountName=" + _username + ")";
_search.PropertiesToLoad.Add("cn");
_result = _search.FindOne();
if (null == _result) { return false; }
_path = _result.Path;
_filterAttribute = (String)_result.Properties["cn"][0];
}
catch (Exception ex) { throw new Exception("Error authenticating user: " + ex.Message); }
return true;
}
public string GetGroups()
{
string r = "";
try
{
Object obj = _entry.NativeObject;
_search = new DirectorySearcher(_entry);
_search.Filter = "(SAMAccountName=" + _username + ")";
_search.PropertiesToLoad.Add("cn");
_result = _search.FindOne();
if (null != _result)
{
_path = _result.Path;
_filterAttribute = (String)_result.Properties["cn"][0];
_search = new DirectorySearcher(_path);
_search.Filter = "(cn=" + _filterAttribute + ")";
_search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
_result = _search.FindOne();
int propertyCount = _result.Properties["memberOf"].Count;
String dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (String)_result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex) { return null; }
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
r = groupNames.ToString();
}
}
catch (Exception ex) { throw new Exception("Error obtaining group names: " + ex.Message); }
return r;
}
}
}
在從Visual Studio 2010調試時運行它時,它工作正常。但在IIS7上,它給出了一個錯誤An operations error occured.
不知道如何在IIS下調試,儘管我確信它是可能的。如果我完全忽略GetGroups()
並發表評論,它的工作原理,但我當然需要這些組名稱。
PS - 是的,上面的代碼與原始代碼沒什麼兩樣,我調整它重新使用一些冗餘的東西。然而,在我改變這個之前,我確實有這個問題。
這是一個目錄權限問題?換句話說:連接到IIS服務器的用戶(或計算機)是否有權執行查詢?在我的場景中,我的開發框不是目錄的成員。我會查詢,幾乎任何查詢都會得到一個DirectoryServicesCOMException。 –
如果是這種情況,那麼它會是另一種方式,因爲正在工作的是標準用戶,並且IIS機器是域管理員,但是隨後IIS又在會話0中運行。兩臺機器都是同一個子網中的同一個域。 –
在我們的環境中,我們必須將應用程序池的標識設置爲有權訪問該目錄的用戶。 –