0

I'd like check the the login and the password match with the AD info. I tried with this piece of coode but I get an exception on FindOne (bad username or password .. but they are correct). I know there is the PrincipalContext solution but I need to be able to set the server (Production, Dev, ...)

Thanks,

var Ad = new DirectoryEntry("LDAP://server1.domain.com", username, password);

var AdSearcher = new DirectorySearcher(Ad);
AdSearcher.Filter = String.Format("(anr={0})", username);
AdSearcher.PropertiesToLoad.Add("sAMAccountName");
AdSearcher.PropertiesToLoad.Add("displayName");

var AdSearcherResults = AdSearcher.FindOne();
var userFullName = AdSearcherResults.Properties["displayName"][0].ToString();
var userUid = AdSearcherResults.Properties["sAMAccountName"][0].ToString();

if (Membership.ValidateUser(username, userUid))
    return true;
return false;   

Update1 I tried this too :

using (var context = new PrincipalContext(ContextType.Domain, "server1.domain.com"))
{
    var isValid = context.ValidateCredentials(username, password);
} 

My computer is not connected on the domain but should be work I think.

TheBoubou
  • 19,487
  • 54
  • 148
  • 236
  • See [my response to this other SO question](http://stackoverflow.com/questions/290548/c-sharp-validate-a-username-and-password-against-active-directory/499716#499716) – marc_s Oct 30 '12 at 08:44
  • And also: the `PrincipalContext` class **has** overloaded constructors to allow you to define exactly what domain and what container inside that domain to validate against .... [see the **wonderful** and freely available MSDN documentation on this topic!](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalcontext.principalcontext.aspx) – marc_s Oct 30 '12 at 08:45

1 Answers1

0

My code for ActiveDirectory Auth.

    public DirectoryEntry connDirectory(string usr, string pwd)
    {

        string ip = iniMan.IniRead("LDAP", "adres");
        DirectoryEntry oDE;
        oDE = new DirectoryEntry(ip, usr, pwd, AuthenticationTypes.Secure);
        return oDE;
    }
    public bool AD_Login(string kullanici_adi, string sifre)
    {
        try
        {
            DirectoryEntry entLogin = connDirectory(kullanici_adi, sifre);
            object loginObj = entLogin.NativeObject;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

    }
    void TestMetod(){
     if(AD_Login("ozan","ozan"){
      //ok
     }
    }
Ozan ÇAKİN
  • 163
  • 15