<$BlogRSDUrl$>

Friday, January 23, 2004

new blog 

I've started a newer, fresher, better blog - head over there now! Oh, it's also crispier and more fragrant.

Thursday, January 22, 2004

user authentication 

Ever so often I get totally baffled, surprised, and even emotional when I see the way some developers authenticate users in their ASP sites.
Last week I spoke to a guy who wrote static methods to encrypt and decrypt credentials, as well as classes to do the validation and authentication for the site. I guess this all carries over from days before .NET (can you imagine that?!) where this had to be done often enough. With the lovely .NET foundation beneath you, it's so easy to use the built-in methods provided. Here's how you authenticate using ASP.NET's "Forms Authentication Mode" and encrypted user credentials in a database.

Authenticated users are issued with a cookie. Unauthenticated users are redirected via client-side HTTP to an authentication-form, where the cookie is issued. Authentication can happen in any way the developer finds fit. I find using the built-in .NET support for MD5 encryption suffices.

Let's set it up. First, in your web.config file, set your authentication-mode:

<authentication mode="Forms">
    <forms name=".ASPXAUTH" protection="All" timeout="60" loginUrl="Login.aspx" />
</authentication>

This would redirect the client to a page named Login.aspx if the user is not authenticated. Once authenticated, a cookie named .ASPXAUTH will be issued to the user, who will hence be authenticated on all other pages.

Create a simple login-page named Login.aspx, and do the following in the click-event for your 'submit' button in code-behind:

private void cmdSubmit_ServerClick(object sender, System.EventArgs e)
{
    DataSet ds = new DataSet();
    //I'm leaving the exercise of building a dataset containing usernames & (encrypted) passwords
    //to the reader.

    String cmd = "username='" + txtUsername.Text + "'";
    DataTable users = ds.Tables[0];
    DataRow[] matches = users.Select(cmd);

    if (matches != null && matches.Length > 0
    {
        DataRow row = matches[0];
        string hashedpwd =
            FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5");
        String pass = (String)row["password"];
        if(0 != String.Compare(pass, hashedpwd, false))
        {
            result.InnerHtml = "Invalid Credentials: Please try again.";
        }
        else
        {
            FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
        }
    }
    else
    {
        result.InnerHtml = "Invalid Credentials: Please try again.";
    }
}

Notice the use of the HashPasswordForStoringInConfigFile-method. I chose the MD5 encryption algorythm here, but the method also accepts "SHA1" as a parameter. No need for customized encryption classes!

To validate user-authentication on pages in your app, do the following in the Page_Load events:

private void Page_Load(object sender, System.EventArgs e)
{
    if(!User.Identity.IsAuthenticated)
    {
        Response.Redirect("login.aspx");
    }
}

Once a client hits any page in your app, validation will fail, and redirection to your login-page will occur. After authentication, the user will be redirected to the originally requested page.

More info on Forms Authentication methods is available here.

This page is powered by Blogger. Isn't yours?