2

I have a Windows Service (running as the Local System user) that needs to validate a user based on username and password, in addition to checking if the user belongs to the group WSMA. My current code is like this:

var pc = new PrincipalContext(ContextType.Machine);
using (pc)
{
  try
  {
    if (pc.ValidateCredentials(username, password))
    {
      using (var groupEntry = new DirectoryEntry("WinNT://./WSMA,group"))
      {
        foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
        {
          using (var memberEntry = new DirectoryEntry(member))
          {
            if (memberEntry.Path.ToLower().EndsWith(username.ToLower()))
            {
              return new LoginResult{ success = true };
            }
          }
        }
      }
    }
    return new LoginResult{ success = false };
  }
  catch (PrincipalOperationException poe)
  {
    if (poe.ErrorCode == -2147023688)
    {
      return new LoginResult { Success = false, ErrorMessage = "Password expired" };
    }
    throw poe;
  }
}

This all works as it should, as long as I'm connected to the network, but if I plug out my network cable, then the ValidateCredentials call give me the following error message:

FileNotFoundException unhandeled by user code. The network path was not found.

I guess this has something to do with AD, but I only need to check the local users, and not domain users so a network access should not be required.

Any way to do this using the PrincipalContext, or some other way that will work in a disconnected scenario?

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • Not very sure but since its (`PrincipalContext`) a part of `DirectoryServices` it could fail since you don't have a domain and hence no `Directory` – V4Vendetta May 24 '12 at 06:29
  • @V4Vendetta - It works great without being connected to a domain when it's set to ContextType.Machine instead of ContextType.Domain, and it verifies against the local users, but it simply wont work without network access (even if i think it does not use the network access for anything). – Øyvind Bråthen May 24 '12 at 06:33
  • It looks like this example is working: http://stackoverflow.com/questions/252882/get-a-list-of-members-of-a-winnt-group – HW90 May 24 '12 at 06:35
  • @HW90 - That question deals with the group issue. My code fails before even trying to determine group membership on the `ValidateCredentials` line. – Øyvind Bråthen May 24 '12 at 06:44

1 Answers1

3

Here's a way to logon the User (and thus check that it's a valid user/pass): MSDN Link

I guess this should work disconnected, too, if you use a local account

Rajeev Bera
  • 2,021
  • 1
  • 16
  • 30
MichelZ
  • 4,214
  • 5
  • 30
  • 35
  • This is using the LogonUser Win32 API that has some requirements on the access that the user running it uses. Luckily, my service is running as Local System, so it worked just fine. Thanks a lot :) – Øyvind Bråthen May 24 '12 at 08:23