2
votes

I read millions of posts about active directory authentication, but didn't find any post about my problem specifically.

I want to authenticate user against active directory with MVC4 forms authentication and letting to insert domain name as an option:

acc: domain.com\username  or  username
pwd: password

My company has 20 subdomains and I need to authenticate each domain and that's why I don't like option to keep my domains in app config and choose from it.

Directory entry:

var directoryEntry = new DirectoryEntry("LDAP://" + domain, userName, password);

would be great, but if user dont put domain in front of username ? i will get exception and user wont be authenticated. I want to have a method:

public bool AuthenticateUser(string username, string password)
{
   Checking if username has domain name included;
   use some kind of authetication method;
   returns true/false;
}

with manually parsing username and checking all if conditions and so on, my method will look like crap, maybe it is some kind of parameter in app config to write that would give me an option to let user enter domain\username or just username and i could then get domain + username or just username and then authenticate user against AD.

Thanks in advance.

1

1 Answers

2
votes

You could try to use double authentication solution using both Membership and PrincipalContext

public bool ActiveDirectoryAuthentication(string username, string password)
    {
        var splittedCredentials = username.Split(new[] { "\\" }, StringSplitOptions.None);
        switch (splittedCredentials.Length)
        {
            case 1:
                {
                    var authenticated = Membership.ValidateUser(username, password);
                    if (authenticated)
                    {
                        FormsAuthentication.SetAuthCookie(username, false);
                    }
                    return authenticated;
                }
            case 2:
                {
                    var principalContext = new PrincipalContext(ContextType.Domain, splittedCredentials[0]);

                    using (principalContext)
                    {
                        var authenticated = principalContext.ValidateCredentials(splittedCredentials[1], password);

                        if (authenticated)
                        {
                            FormsAuthentication.SetAuthCookie(splittedCredentials[1], false);
                        }
                        return authenticated;
                    }
                }
            default:
                return false;
        }
    }
  • Before that don't forget to validate user inputs
  • Firstly split Login string
  • If user has not entered domain use Membership
  • If user has entered domain name use PrincipalContext
  • In case other event occurred you will return false