2

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.

4

1 回答 1

2

您可以尝试同时使用 Membership 和 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;
        }
    }
  • 在此之前不要忘记验证用户输入
  • 首先拆分登录字符串
  • 如果用户还没有进入域使用会员
  • 如果用户输入了域名使用 PrincipalContext
  • 如果发生其他事件,您将返回 false
于 2013-08-01T09:02:24.147 回答