简体   繁体   中英

LDAP Authentication in ASP.Net MVC

I want to be able to authenticate a user by using their domain UserId and Password, but the default ASP.Net MVC application allows the user to register a userId and password and then log in. How can I do this?

I don't want the user to be able to register; however, he should be able to enter his windows domain userId and password and be authenticated by the domain server.

The solutions I have seen (for example here on Mike's Blog ) do not require the user to enter his/her UserId or password.

How can I get my ASP.Net MVC application to show a log on form and authenticate the user against the windows domain?

Please explain with a sample if possible

This is how to do it in web Apps forms authentication so it may need some adapting for MVC. Use the asp.net membership and roles engine. Setup the provider to use the Active Directory Membership provider AND ALSO use forms for authentication.

<authentication mode="Forms">
  <forms name=".ADAuthCookie" 
         timeout="10"                     
         loginUrl="Login.aspx" 
         defaultUrl="Default.aspx">            
  </forms>

or something like it....

The provider setup will look something like this:

<membership defaultProvider="DomainLoginMembershipProvider">
  <providers>
    <add name="DomainLoginMembershipProvider"           
             type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"           
         connectionStringName="ADConnectionString"
         connectionProtection="Secure"
         connectionUsername="domainuser"
         connectionPassword="pwd"
         attributeMapUsername="sAMAccountName" 
         enableSearchMethods="false"/>
  </providers>
</membership>

The connection protection, user name and pwd are for the account that has access to query AD on behalf of the system. Depending on the security of your network this may have to be setup or you won't be able to query AD to authenticate the user.

Your connection string will look something like:

<connectionStrings>
  <add name="ADConnectionString"
       connectionString="LDAP://servername:port#/DC=domainname"/>
</connectionStrings>

The connection string can take many forms so you may have to research it for your environment.

For the login page you might have to execute the authentication method and test...

    e.Authenticated = Membership.ValidateUser(username, password);
    if (e.Authenticated == false)...

Stephen Shackow's book "Professional ASP.Net 2.0 Security, Membership, and Role Management" has a good coverage on using AD Membership (Chapter 12). It's not in the context of MVC but the configuration and setup would be the same.

thanks for pointing me the right direction, this is what i ended up doing

        <authentication mode="Forms">
              <forms loginUrl="~/Account/LogOn" timeout="10"/>
        </authentication>                  

 public bool ValidateUser(string userName, string password)
        {
            bool validation;
            try
            {
                LdapConnection ldc = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
                NetworkCredential nc = new NetworkCredential(userName, password, "DOMAIN NAME HERE");
                ldc.Credential = nc;
                ldc.AuthType = AuthType.Negotiate;
                ldc.Bind(nc); // user has authenticated at this point, as the credentials were used to login to the dc.
                validation = true;
            }
            catch (LdapException)
            {
                validation = false;
            }
            return validation;
        }

I don't like the fact that I am using the catch on the try block to determine if the users validation was successful, but I couldn't find another way around it.

I think you are misunderstanding the blog post you referenced. The user id and password supplied in the web.config file are the ones used by the ActiveDirectoryMembershipProvider to connect to AD, not the ones supplied by the user. Essentially what he is saying is to swap out the SQL membership provider for an AD membership provider and use the code as written to get it to work with AD. That's exactly what you need to do. If you don't want to use the membership provider code at all, you can use the PrincipalContext.ValidateCredentials method on a principal context for the domain of interest to validate the credentials passed into the Login method.

using (PrincipalContext context = new PrincipalContext( ContextType.Domain, "domain" )) {
    if (context.ValidateCredentials( username, password))
    {
        // log them in
    }
    else
    {
       // set up error message and rerender view
    }
}

i couldnt find System.Web.Security.ActiveDirectoryMembershipProvider.dll where to find ? also i search in memebership & i found this

<membership defaultProvider="LdapMembershipProvider">
    <providers>
        <add name="LdapMembership"
            type="Microsoft.Office.Server.Security.LDAPMembershipProvider,
            Microsoft.Office.Server,
            Version=12.0.0.0, Culture=neutral,
            PublicKeyToken=71E9BCE111E9429C"
            server="DC"
            port="389"
            useSSL="false"
            userDNAttribute="distinguishedName"
            userNameAttribute="sAMAccountName"
            userContainer="CN=Users,DC=userName,DC=local"
            userObjectClass="person"
            userFilter="(|(ObjectCategory=group)(ObjectClass=person))"
            scope="Subtree"
            otherRequiredUserAttributes="sn,givenname,cn"/>
    </providers>
</membership>

LdapConnection是System.DirectoryServices.Protocols命名空间的成员(您必须将System.DirectoryServices.Protocols库添加到您的引用)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM