2

I need some C# code to validate a windows credential, the account maybe a local account or a domain account.

Please give some ideas about how to do it.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jerrylk
  • 379
  • 5
  • 19
  • 1
    Idea - use your favorite search engine (Google, Bing,...) and type in title of your post. – Alexei Levenkov Jan 08 '14 at 02:30
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jan 08 '14 at 02:33

1 Answers1

5

Depends on your version of .NET that you are using. If you are using .NET version that contains System.DirectoryServices.AccountManagement you can do the following:

 bool valid = false;

 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
 {
     valid = context.ValidateCredentials(username, password);
 }

Change ContextType.Domain to ContextType.Machine for the local machine. You can also try to impersonate the user by querying Active Directory or attempting to force a login to the local system using something like this. I would recommend the above approach instead though.

public bool IsAuthenticated(string server, string username, string password)
{
    bool authenticated = false;

    try
    {
        DirectoryEntry entry = new DirectoryEntry(server, username, password);
        object nativeObject = entry.NativeObject;
        authenticated = true;
    }
    catch (DirectoryServicesCOMException cex)
    {
        //not authenticated; reason why is in cex
    }
    catch (Exception ex)
    {
        //not authenticated due to some other exception [this is optional]
    }

    return authenticated;
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
AnthonyBCodes
  • 342
  • 2
  • 13