简体   繁体   中英

PrincipalContext.ValidateCredentials with cached credentials in C#

I'm trying to authenticate users in an application using a domain controller with code like this:

PrincipalContext pcon = new PrincipalContext(ContextType.Domain, domain);
password_ok = pcon.ValidateCredentials(username, password);

That works fine as long as the domain server is online but if there is no domain server the previous code fails with a PrincipalServerDownException exception. What I'm trying to do is to make my application use the windows cached credentials if the server is down just like Windows do: you may login into windows with a domain user even if the domain server is down. Can I do that in C#?

Thank you very much in advance.

For posterity, this is how I solved my problem:

bool dmainNotAvailable = false;
PrincipalContext pcon = null;
try
{
pcon = new PrincipalContext(ContextType.Domain, domain);

}
catch (System.DirectoryServices.AccountManagement.PrincipalServerDownException ex)
{
   domainNotAvailable = true;

    try
    {
       pcon = new PrincipalContext(ContextType.Machine, Environment.MachineName);
    }
    catch (Exception ex2)
    {
       throw new Exception(ex2);
    }
}
string realUserName = !domainNotAvailable ? username : $"{domain}\\{username}";
passwordOk = pcon.ValidateCredentials(realUserName, password);

This will also work:

string userName = $"{domain}\\{user}";
PrincipalContext pcon = new PrincipalContext(ContextType.Machine, Environment.MachineName);
passworkOk = pcon.ValidateCredentials(userName, password);

The second solution will try lo login using the cached credentials and if there is no info then will try to login using the domain controller.

On both solutions the domain user must be added first to the local computer in order to have the credentials cached.

That's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM