Tuesday, July 19, 2011

Forms Authentication with asp.net

This is a step by step guide to enable forms authentication in your web application. We will be authenticating against and LDAP directory.

Step 1: Add this to your web.config file. Tow main parameters below are the loginUrl and defaultUrl

<configuration> 
  <system.web>   
    <authentication mode="Forms">
      <forms loginUrl="Login.aspx"
             protection="All"
             timeout="30"
             name=".ASPXAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="Home.aspx"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>

Step 2: Create a class that handles the LDAP authentication. You might have to add a reference to System.DirectoryServices to your project

public class LDAPAuthenticator
{
    private static string USurl = "LDAP://<IP Address>:389/DC=<value>,DC=<value>";
    public HttpCookie Ticket { get; set; }
    public LDAPAuthenticator()
    { }

    public string Authenticate(string Username, string Password)
    {
        string AUTHSTATUS = string.Empty;
        DirectoryEntry USentry = new DirectoryEntry(USurl, Username, Password);       
        try
        {
            //Bind to the native AdsObject to force authentication.           
            DirectorySearcher USsearch = new DirectorySearcher(USentry);
            USsearch.Filter = "(sAMAccountName=" + Username + ")";
            USsearch.PropertiesToLoad.Add("cn");
            SearchResult USresult = USsearch.FindOne();
            if (null == USresult)
            {
                AUTHSTATUS = "FAIL";              
            }
            else
            {
                AUTHSTATUS = "PASS";
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                    Username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30), // value of time out property
                    false, // Value of IsPersistent property
                    String.Empty,
                    FormsAuthentication.FormsCookiePath);
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket);
                this.Ticket = authCookie;
                return AUTHSTATUS;
            }           
        }
        catch (Exception ex)
        {
            AUTHSTATUS = ex.Message;
            return AUTHSTATUS;
        }
        return AUTHSTATUS;
    }
}

Step 3: Create a web form called Login.aspx and a code behind file Login.aspx.cs . Include a username field and password field and a login Button. On the submit button/login button click event add this code

protected void LoginButton_Click(object sender, EventArgs e)
    {
        LDAPAuthenticator auth = new LDAPAuthenticator();
        string AUTHSTATUS = auth.Authenticate(UserNameTextBox.Text, PasswordTextBox.Text);
        if (AUTHSTATUS.Trim() == "PASS")
        {
            Session.Add("SESSIONUSER", sessionuser);
            Response.Cookies.Add(auth.Ticket);
            Response.Redirect("Home.aspx", false);           
        }
        else
        {
            AUTHSTATUSLabel.Text = AUTHSTATUS;
        }
    }   

Thats it.

Cheers
Bhushan

No comments:

Post a Comment