Public Code Review

time to read 19 min | 3663 words

Okay, so I need to check if a username/password are valid on a given Active Directory domain (which is not the one that I am runing on). Here is the options that I came up with:

public bool IsValidLogin(string username, string password)

{

       IntPtr userId = IntPtr.Zero;

       if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE,

              LOGON32_PROVIDER_DEFAULT,

              ref userId))

       {

              CloseHandle(userId);

              return true;

       }

       return false;

}

I am not sure that the above code works for remote domains, and I am not sure that it works in all cases. LOGIN32_LOGIN_INTERACTIVE seems to be something that you shouldn't do on servers, but it doesn't work unles I run it with it.

Here is what MSDN seems to recommend:

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(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)

  {

    throw new Exception("Error authenticating user. " + ex.Message);

  }

  return true;

}

I have numerous style, guidelines, performance, and best practices issues with this code.

Any other ways you can recommend?

I should note that this is actually the first time that I am interfacing with AD, although my company is doing a lot of work in this area, I always was the database/business functionality guy so far.