4

I'm trying to use AD LDS for user authentication in my MVC app. I've managed to write some code that allows me to create/edit/delete users and groups, but i can't seem to authenticate them. Here is my sample code:

using( var context = new PrincipalContext(ContextType.ApplicationDirectory, "Lenovo_T61-LapT",
                                    "CN=Kontrahenci,DC=TestApp,DC=local"))
{
    var userName = "avg.joe";
    var email = "avg.joe@smwhr.us";
    var password = "123456";
    var user = new UserPrincipal(context)
    {
        Name = userName,
        EmailAddress = email
    };
    user.SetPassword(password);
    user.Save();
    if (context.ValidateCredentials(userName , password, ContextOptions.SimpleBind))
        Console.WriteLine("Hooray!");

    user.Dispose();
}

Unfortunately this never gets to "Writeline" giving only an error that either the password or username are incorrect.

I've played around with ContextOptions but without any luck.

Any ideas?

Szymon Seliga
  • 784
  • 5
  • 23

1 Answers1

8

So I've found the solution which I posted on a similar question.

What I did, and works for me, is when calling ValidateCredentials I modified the username a bit:

bool auth = context.ValidateCredentials(
                            String.Format("CN={0},CN=Kontrahenci,DC=TestApp,DC=loc",
                                          userName), 
                            password);

Hope this helps.

Community
  • 1
  • 1
Szymon Seliga
  • 784
  • 5
  • 23
  • 1
    As shown in the answer above - using the DistinguishedName for the userName parameter instead of the sAMAccountName solved it for me. But I wanted to add to that answer that I DID NOT have to set the ContextOptions to SimpleBind. – ambidexterous Nov 15 '16 at 22:07