Active Directory Authentication for ASP.NET Website Users


ASP.NET membership provides the ability to authenticate users to your web application using forms based authentication against a database of users or directory services.  This article explains the steps required to provide authentication against Active Directory, either for new sites with no authentication, or for existing sites using database authentication.

Step 1 – Set up the Active Directory connection string
The Active Directory connection string is simliar to the database connection string used in ASP.NET, except that it references an LDAP address.  The connection string is specified in the web.config file.
The following string will authenticate users in the entire company.com.au tree:

<connectionStrings>
    <add name="ADConnectionString" 
    connectionString="LDAP://company.com.au/DC=company,DC=com,DC=au"/>
</connectionStrings>

If you want to restrict authentication to a particular OU, then you specify it in the connection string like so:

<connectionStrings>
    <add name="ADConnectionString" 
    connectionString="LDAP://dept.company.com.au/CN=dept,DC=company,DC=com,DC=au"/>
</connectionStrings>

Step 2 – Configure the Membership provider

In your web.config file, create or change the following entry to configure the Membership provider for Active Directory within the <system.web> section:
 
<membership defaultProvider="MyADMembershipProvider">
    <providers>
        <add name="MyADMembershipProvider" 
        type="System.Web.Security.ActiveDirectoryMembershipProvider, 
        System.Web, Version=2.0.0.0, Culture=neutral, 
        PublicKeyToken=b03f5f7f11d50a3a" 
        connectionStringName="ADConnectionString" 
        attributeMapUsername="sAMAccountName"/>
    </providers>
</membership>

The connectionStringName attribute should match the name of the connection string you created in Step 1. 
You can configure the credentials used to access Active Directory using the connectionUserName andconnectionPassword attributes.  If you leave these blank then your application's process identity is used to access Active Directory, regardless of whether your application uses impersonation.

Step 3 – Configure the Authentication and Authorization parameters
In your web.config file, create or change the following entry to configure the authentication and authorization parameters for Active Directory within the <system.web> section:

<authentication mode="Forms">
    <forms name=".ADAuthCookie" timeout="43200"/>
</authentication>
<authorization>
    <deny users="?"/>
    <allow users="*"/>
</authorization>

The authorization settings above require every user to authenticate before accessing your web application.  ASP.NET will automatically redirect these users to a Login.aspx page.

Step 4 – Create a Login page
The simplest way of creating the login page (which must be called Login.aspx) is by using the ASP.NET Login control as the following example demonstrates:

<form id="form1" runat="server">
<asp:Login ID="Login1" runat="server">
    <LayoutTemplate>
    <p>
        <asp:TextBox runat="server" ID="Username" />
    </p>
    <p>
        <asp:TextBox runat="server" ID="Password" TextMode="Password" />
    </p>
    <p>
        <asp:CheckBox ID="RememberMe" runat="server" />
    </p>
        <asp:Button ID="btnLogin" runat="server" CommandName="Login" />
    </LayoutTemplate>
</asp:Login>
<br />
<asp:Label ID="lblLoginErrorDetails" runat="server" />
</form>

If you are using the Login control, you MUST name your user name and password text boxes exactly as shown in the example.
The Login control can also provide error checking through the built in LoginError subroutine:


C#
// Handles LoginUser.LoginError
   
protected void
Login1_LoginError(object sender, System.EventArgs e)
    {
      
if (LoginUser.UserName ==
string.Empty & LoginUser.Password ==
string.Empty)
      
{
          
lblLoginErrorDetails.Text = "Please enter
your username and password."
;
      
}
      
else if
(LoginUser.UserName == string.Empty)
      
{
          
lblLoginErrorDetails.Text = "Please enter
your username."
;
      
}
      
else if
(LoginUser.Password == string.Empty)
      
{
          
lblLoginErrorDetails.Text = "Please enter
your password."
;
      
}
      
else
      
{
          
MembershipUser userInfo =
Membership.GetUser(LoginUser.UserName);
          
LoginError.Visible = "True";
          
if (userInfo ==
null
)
          
{
              
lblLoginErrorDetails.Text = "There is no user
in the database "
+

                  
"with the username " +
LoginUser.UserName + ". Please try again.";
          
}
          
else
          
{
              
if (!userInfo.IsApproved)
              
{
                  
lblLoginErrorDetails.Text = "Your account has
not yet been "
+

                      
"approved. Please try again later.";
              
}
              
else if
(userInfo.IsLockedOut)
   
            {
                  
lblLoginErrorDetails.Text = "Your account has
been locked "
+

                      
"out due to maximum incorrect login attempts. Please " +

                      
"contact the site administrator.";
              
}
              
else
              
{
                  
lblLoginErrorDetails.Text = "Your password is
incorrect, "
+

                      
"please try again.";
              
}
          
}
      
}
    }


VB.NET

   
Protected Sub
Login1_LoginError(ByVal sender
As Object,
ByVal e As
System.EventArgs) '
Handles LoginUser.LoginError
      
If LoginUser.UserName =
String.Empty And
LoginUser.Password = String.Empty
Then
          
lblLoginErrorDetails.Text = "Please enter
your username and password."
      
ElseIf LoginUser.UserName =
String.Empty Then
          
lblLoginErrorDetails.Text = "Please enter
your username."
      
ElseIf LoginUser.Password =
String.Empty Then
          
lblLoginErrorDetails.Text = "Please enter
your password."
      
Else
          
Dim userInfo As
MembershipUser =
Membership
.GetUser(LoginUser.UserName)
          
LoginError.Visible = "True"
          
If userInfo Is
Nothing Then
              
lblLoginErrorDetails.Text = "There is no user
in the database "
& _
              
"with the username " &
LoginUser.UserName & ". Please try again."
          
Else
              
If Not
userInfo.IsApproved Then
                  
lblLoginErrorDetails.Text = "Your account has
not yet been "
& _
                  
"approved. Please try again later."
              
ElseIf userInfo.IsLockedOut
Then
                  
lblLoginErrorDetails.Text = "Your account has
been locked "
& _
      
             "out due to maximum incorrect
login attempts. Please "
& _
                  
"contact the site administrator."
              
Else
                  
lblLoginErrorDetails.Text = "Your password is
incorrect, "
& _
                  
"please try again."
              
End If
          
End If
      
End If
   
End Sub


That’s all you should need to allow your users to log on.  This is just the beginning of using Active Directory authentication for your web site, stay tuned for further articles in this series!

Popular Posts