Question

I want to know if my user is an active directory account n throught domain ,login and password. I test this function :

public void ValidateCredentials(string sUserName, string sPassword)
    {
        PrincipalContext adContext = new PrincipalContext(ContextType.Domain);

        using (adContext)
        {
           bool tes= adContext.ValidateCredentials(sUserName, sPassword);
        }
    }

but i always return true even the domain,users and password are fault.

Was it helpful?

Solution

Alternately, you can try this...

try
{
    var credentials = new NetworkCredential(sUserName, sPassword);

    using (var connection = new LdapConnection(domainName))
    {
        connection.AuthType = AuthType.Kerberos 
        connection.Bind(credentials);
    }

    return true;
}
catch
{
    //handle errors as you see fit
    return false;
}

OTHER TIPS

I personally use this code to do that via P/Invoke and I've never had any problems with it:

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

public enum LogonType
{
    Interactive = 2,
    Network = 3,
    Batch = 4,
    Service = 5,
    Unlock = 7,
    NetworkClearText = 8,
    NewCredentials = 9,
}

public enum LogonProvider
{
    LOGON32_PROVIDER_DEFAULT = 0,
    LOGON32_PROVIDER_WINNT35 = 1,
    LOGON32_PROVIDER_WINNT40 = 2,
    LOGON32_PROVIDER_WINNT50 = 3
}

public static bool LdapAuthentication(string domain, string user, string password, Configurator cfg)
{
    try
    {
        LogonType lt = LogonType.Network;

        IntPtr token = IntPtr.Zero;
        return (LogonUser(user, domain, password, (int)lt, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token));
    }
    catch
    {
        return (false);
    }
}

If you still have some problems, maybe you can try to change the LogonType.

Please mark this answer as accepted if it responds to your question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top