- In C#, how do I authenticate a user on a network machine?
- PrincipalContext pc =
- new PrincipalContext(ContextType.Domain, exampleMachineDomain);
- return pc.ValidateCredentials(testUserUsername, testUserPassword);
- using System.Security;
- using System.DirectoryServices.AccountManagement;
- public struct Credentials
- {
- public string Username;
- public string Password;
- }
- public class Domain_Authentication
- {
- public Credentials Credentials;
- public string Domain;
- public Domain_Authentication(string Username, string Password, string SDomain)
- {
- Credentials.Username = Username;
- Credentials.Password = Password;
- Domain = SDomain;
- }
- public bool IsValid()
- {
- using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
- {
- // validate the credentials
- return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
- }
- }
- }
- PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
- // define a "query-by-example" principal - here, we search for a UserPrincipal
- UserPrincipal qbeUser = new UserPrincipal(ctx);
- // if you're looking for a particular user - you can limit the search by specifying
- // e.g. a SAMAccountName, a first name - whatever criteria you are looking for
- qbeUser.SamAccountName = "johndoe";
- // create your principal searcher passing in the QBE principal
- PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
- // find all matches
- foreach(var found in srch.FindAll())
- {
- // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
- }
- PrincipalContext pc =
- new PrincipalContext(ContextType.Machine, exampleMachineDomain);
- return pc.ValidateCredentials(testUserUsername, testUserPassword);
- private static bool AuthenticateUserOnRemote(string server, string userName, string password)
- {
- var connected = PinvokeWindowsNetworking.connectToRemote(server, userName, password);
- var disconnected = PinvokeWindowsNetworking.disconnectRemote(server);
- return connected == null;
- }