Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 2.26 KB  |  hits: 47  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. In C#, how do I authenticate a user on a network machine?
  2. PrincipalContext pc =
  3.     new PrincipalContext(ContextType.Domain, exampleMachineDomain);
  4. return pc.ValidateCredentials(testUserUsername, testUserPassword);
  5.        
  6. using System.Security;
  7. using System.DirectoryServices.AccountManagement;
  8.     public struct Credentials
  9.     {
  10.         public string Username;
  11.         public string Password;
  12.     }
  13.     public class Domain_Authentication
  14.     {
  15.         public Credentials Credentials;
  16.         public string Domain;
  17.         public Domain_Authentication(string Username, string Password, string SDomain)
  18.         {
  19.             Credentials.Username = Username;
  20.             Credentials.Password = Password;
  21.             Domain = SDomain;
  22.         }
  23.         public bool IsValid()
  24.         {
  25.             using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
  26.             {
  27.                 // validate the credentials
  28.                 return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
  29.             }
  30.         }
  31.     }
  32.        
  33. PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
  34.  
  35.     // define a "query-by-example" principal - here, we search for a UserPrincipal
  36.     UserPrincipal qbeUser = new UserPrincipal(ctx);
  37.  
  38.     // if you're looking for a particular user - you can limit the search by specifying
  39.     // e.g. a SAMAccountName, a first name - whatever criteria you are looking for
  40.     qbeUser.SamAccountName = "johndoe";
  41.  
  42.     // create your principal searcher passing in the QBE principal    
  43.     PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
  44.  
  45.     // find all matches
  46.     foreach(var found in srch.FindAll())
  47.     {
  48.         // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
  49.     }
  50.        
  51. PrincipalContext pc =
  52.     new PrincipalContext(ContextType.Machine, exampleMachineDomain);
  53. return pc.ValidateCredentials(testUserUsername, testUserPassword);
  54.        
  55. private static bool AuthenticateUserOnRemote(string server, string userName, string password)
  56.             {
  57.                 var connected = PinvokeWindowsNetworking.connectToRemote(server, userName, password);
  58.                 var disconnected = PinvokeWindowsNetworking.disconnectRemote(server);
  59.                 return connected == null;
  60.             }