Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do I authenticate a user on a network machine?

In C#, how do I authenticate a user on a network machine? For example, I want to authenticate the user testuser with password testpassword on the machine EXAMPLEMACHINE from a different machine which is network-connected to EXAMPLEMACHINE. For example, I am on MYMACHINE and I want to authenticate testuser with testpassword on EXAMPLEMACHINE.

I have tried the following but it keeps telling me that, The LDAP server is unavailable:

PrincipalContext context =
    new PrincipalContext(ContextType.Domain, exampleMachineDomain);
return context.ValidateCredentials(username, password);
like image 577
Alexandru Avatar asked Jan 23 '12 14:01

Alexandru


2 Answers

If you are not using Active Directory, you could use something like this:

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);
            }
        }
    }

If you are using Active Directory, you could use something like this:

 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.....          
    }
like image 54
MethodMan Avatar answered Nov 15 '22 00:11

MethodMan


If your machines are not in a domain, you need to use ContextType.Machine:

PrincipalContext context = 
    new PrincipalContext(ContextType.Machine, exampleMachineDomain);
return context.ValidateCredentials(username, password);
like image 32
Christoph Fink Avatar answered Nov 14 '22 23:11

Christoph Fink