ユーザーが属するグループを取得しようとすると、「ログオン失敗: 不明なユーザー名またはパスワードが正しくありません」というエラーが表示されます。ユーザー認証は正常に機能しますが、これが理解できません。AD に対してユーザーを適切に認証するにはどうすればよいですか? グループ名を取得できません。ユーザーIDとパスワードを取得します。認証を扱うクラスがあります。
if ((true == adAuth.IsAuthenticated(sDomain, sID, sPassword)))
{
string sGroups = adAuth.GetGroups();
これは認証クラスです。
public class LdapAuthentication
{
string _path;
string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try {
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null)) {
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = Convert.ToString(result.Properties["cn"][0]);
}
catch (Exception ex) {
throw new Exception("Error authenticating user. " + ex.Message);
//return false;
}
return true;
}
public string GetGroups()
{
//DirectorySearcher search = new DirectorySearcher(_path);
// Use following two lines instead of the above to handle cases of authenticatin against an LDAP server other than local AD domain
DirectoryEntry deSearchRoot = new DirectoryEntry(_path);
DirectorySearcher search = new DirectorySearcher(deSearchRoot);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try {
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn = null;
int equalsIndex = 0;
int commaIndex = 0;
int propertyCounter = 0;
for (propertyCounter = 0; propertyCounter <= propertyCount - 1; propertyCounter++) {
dn = Convert.ToString(result.Properties["memberOf"][propertyCounter]);
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if ((equalsIndex == -1)) {
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
} catch (Exception ex) {
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
IsAuthnticated は合格し、正常に動作します。GetGroups() は、「グループ名の取得エラー」に続いて「ログオン失敗: 不明なユーザー名またはパスワードが正しくありません」を返します (つまり、GetGroups() の例外)。
VS からアプリを実行すると正常に動作しますが、(同じサーバー上で) 公開すると、このように動作します。どんなアイデアでも大歓迎です。