Implementing ASP.Net Forms Authentication with Active Directory Membership Provider

Posted by & filed under .Net, .Net 3.0 / 3.5, ASP.Net.

ActiveDirectoryMembership provider is used manage users against Active Directory, which helps to create Single Sign On for intranet application. Here is a basic implementation, which used to Authenticate users against Active Directory, using Login Control.

We need to modify the web.config, like the implementation of Forms Authentication in ASP.Net.

Create / Add a connection string to active directory database.

<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://DOMAIN.SUBDOMAIN/DC=DOMAIN,DC= SUBDOMAIN "/>
</connectionStrings>

Configure Membership node in the web.config with ActiveDirectoryMembershipProvider.

<membership defaultProvider="MembershipADProvider">
  <providers>
    <add name="MembershipADProvider" 
         type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
         applicationName="dotnetthoughts" 
         connectionStringName=" ADConnectionString " 
         attributeMapUsername="sAMAccountName"/>
  </providers>
</membership>

You can also provide the Username / Password in this using connectionUsername , connectionPassword attributes.

Modify the Authentication mode and Authorization nodes for controlling the access permissions. Currently I am using Forms Authentication defaults. (default.aspx – Home Page, and Login.aspx – Login Page)

<authentication mode="Forms" />
<authorization> 
    <deny users="?" />
    <allow users="*" />
</authorization>

Almost done. Now drag and drop Login control from Toolbox > Login tab to Login.aspx. Run the application, say OK to the Debug mode confirmation from Visual Studio. As we are configured the Authentication provider we don’t need to write any Code to Authentication.

If you don’t want to use login control, you can do something like this in the code behind for the authentication.

if (Membership.ValidateUser(this.txtUsername.Text, this.txtPassword.Text))
{
    FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, false);
}
else
{
    Response.Write("Authentication failed.\nUsername / Password Invalid");
}

Thanks to Sreenaja for the initial implementation. Happy Coding :)

Leave a Reply

CAPTCHA Image
*