Domanda

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.

È stato utile?

Soluzione

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top