How to provide DirectoryEntry.Exists with credentials?

萝らか妹 提交于 2020-01-03 07:17:24

问题


This morning I discovered a nice method (DirectoryEntry.Exists), that should be able to check whether an Active Directory object exists on the server. So I tried with a simple:

if (DirectoryEntry.Exists(path)) {}

Of course it lacks any overloads to provide credentials with it. Because, if credentials are not provided I get this Exception:

Logon failure: unknown user name or bad password. (System.DirectoryServices.DirectoryServicesCOMException)

Is there any other option that gives me the possibility to authenticate my code at the AD server? Or to check the existence of an object?


回答1:


In this case you can't use the static method Exists as you said :

DirectoryEntry directoryEntry = new DirectoryEntry(path);
directoryEntry.Username = "username";
directoryEntry.Password = "password";

bool exists = false;
// Validate with Guid
try
{
    var tmp = directoryEntry.Guid;
    exists = true;
}
catch (COMException)
{
   exists = false; 
}



回答2:


There is no way to do this and I have written a connect issue to hopefully resolve it.

DirectoryEntry.Exists Does Not Accept Credentials




回答3:


Here you can read about impersonation in C#:

  • http://www.codeproject.com/KB/cs/zetaimpersonator.aspx
  • http://www.codeproject.com/KB/system/everythingInAD.aspx



回答4:


So answer to the question: impossible.

Finally write an own method to get the DirectoryEntry by distinguised name, with credentials specified. In both cases of existence/inexistence I got an instance of DirectoryEntry. To check whether it's a valid object returned I do a simple try...catch to see if it results in an Exception. If so, it's invalid.

Nasty check, but it works. Too bad the default .net method DirectoryEntry.Exists doesn't provide an overload to provide credentials just like the DirectoryEntry constructor...




回答5:


If the user who ran the process doesn't have permissions to call DirectoryEntry.Exists, then you can use impersonation.

This may be helpful (discusses impersonation in an AD context): http://www.codeproject.com/KB/system/everythingInAD.aspx

Btw, if you already have credentials of a user who has access to everything you need, why not just the process with that user (e.g. /runas)?



来源:https://stackoverflow.com/questions/4284253/how-to-provide-directoryentry-exists-with-credentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!