SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (31)
  • LINQ (4)
  • Security (2)
  • Silverlight (2)
  • SQL (7)
  • Standards (5)
  • WCF (1)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box

Membership Using ASP.NET AJAX

(Jun 25 2007 - 05:22:27 PM by Timothy Khouri) - [print article]

Previous articles have discussed how to use AJAX to consume web services, call page methods and interact with the Profile API. This article will demonstrate how to perform membership functionality (authentication) with ASP.NET AJAX. Attached will be the full source, including a sample database to keep the login information.

Since this article is primarily about ASP.NET AJAX and how to interact with the ASP.NET Membership API, we are going to assume you already know somewhat about membership, authentication and the like.

So as a quick rundown (very quick), we are going to discuss the pieces that need to already be in place in your application before you mash it up with AJAX.

Basic ASP.NET 2.0 Membership

ASP.NET 2.0 introduced built-in membership functionality that we are going to tap into with ASP.NET AJAX. The pieces needed to use this API are pretty simple, but we are going to list them out here:

  1. Run the ASPNET_REGSQL.exe against your SQL database to include the membership tables, views and stored procedures.
  2. Add the membership configurations to your web.config file.

Adding Membership Functionality To SQL Server

You can use ASPNET_REGSQL.exe with SQL Server 2000, SQL Server 2005 or even SQL Express. If you are using SQL Express (as we will in this article), you won't be able to use the Wizard GUI to configure your database. If you are using SQL Server 2000 or SQL Server 2005, you can just run the executable and you'll get this GUI:

ASPNET_REGSQL.exe GUI

The setup is straight forward using the wizard above. However, if you are going down the SQL Express route, you'll have to run this in the command line:

aspnet_regsql -A all -C "Data Source=.\SQLEXPRESS; Integrated Security=True; User Instance=True" -d "C:\MyWebApp\App_Data\MyDB.mdf"

ASPNET_REGSQL.exe for SQL Express in a command line

Adding Membership Functionality To Your Web.Config

Now that you have your SQL instance configured to include the membership functionality provided by ASP.NET, you'll need to add a few lines to your web.config file to finish the job. First, in the <connectionStrings> section you need to create a new connection string and point it to your SQL instance. Here's the code:

<connectionStrings>
   <add name="myConnection" connectionString="Data Source=.\SQLEXPRESS; AttachDbFileName=|DataDirectory|MyDB.mdf; Integrated Security=True; User Instance=True" />
</connectionStrings>

You'll also need to add the <membership> configuration to your <system.web> config section. Your membership section should look something like this:

<system.web>
   <membership defaultProvider="myMembershipProvider">
       <providers>
           <add name="myMembershipProvider"
               applicationName="myApplication"
               connectionStringName="myConnection"
               enablePasswordReset="true"
               enablePasswordRetrieval="false"
               passwordFormat="Hashed"
               maxInvalidPasswordAttempts="5"
               minRequiredPasswordLength="7"
               minRequiredNonalphanumericCharacters="0"
               requiresQuestionAndAnswer="false"
               requiresUniqueEmail="true"
               passwordAttemptWindow="5"
               passwordStrengthRegularExpression=""
               type="System.Web.Security.SqlMembershipProvider" />
       </providers>
   </membership>
</system.web>

Lastly, you'll need to tell ASP.NET AJAX that you want the ability to interact with the membership API. You'll need to add this section to your web.config as well:

<system.web.extensions>
   <scripting>
       <webServices>
           <authenticationService enabled="true" />
       </webServices>
   </scripting>
</system.web.extensions>

Now that we have the basics out of the way, we can begin to build our site. I'm going to skip ahead to the part where we are adding AJAX functionality now, but you can see all of the source code for this project in the attachment at the end of this article.

Using Membership With AJAX

First we are going to create a simple login form. We'll make it a little fancy by having the form only show up when the user clicks the "login" link (kinda like Digg.com does). We won't need to post back to the server though as we are just going to swap some CSS attributes to make one "panel" hide and the other one show.

Because we are doing all of our code through JavaScript and AJAX, we won't be using ASP.NET server controls. So here is the basic HTML code for the login form:

<a id="login-link" href="javascript:showLogin();">Login</a>
<div id="login-panel" style="visibility: hidden;">
   <fieldset onkeydown="checkForEnter();">
       <label>
           User Name:<input type="text" id="userName" /></label>
       <label>
           Password:<input type="password" id="password" /></label>
       <label class="checkbox" for="rememberMe">
           <input type="checkbox" id="rememberMe" checked="checked" />Remember Me</label>
       <button onclick="setTimeout(loginButton_Click, 0); return false;">
           Login</button>
   </fieldset>
</div>

Just for fun, I've added a few nice things with JavaScript. For starters there is a "checkForEnter" function on the surrounding fieldset. That will "click" the login button if you press the [ENTER] key on your keyboard.

I've also add a 30 second timer (in JavaScript) that will clear the login form if the user has not finished logging in. This will act as an extra security layer (in case someone enterest their info and walks away from the computer before pressing the login button). Those functions are not shown in this article, but it is in the source files that are attached at the end of the article.

Now we'll look at the JavaScript functionality that I coded in the "loginButton_Click" function:

function loginButton_Click() {
   Sys.Services.AuthenticationService.login($get("userName").value,
       $get("password").value, $get("rememberMe").checked, null,
       location.href, loginCallback, errorCallback);
}

This will tap into the ASP.NET AJAX Membership API to perform a basic user login. The first three parameters are familiar (username, password and persistance). The fourth parameter is intentionaly blank (reserved for future use). Parameter five is the "redirect url" (only applies to a successful login attempt). We are just going to refresh the current page, so I used the "location.href" property.

The next two parameters are functions that you will build in JavaScript to handle if the user enters a bad password, or if there was some other error. Those functions are also in the attached source files below.

The End Result

When you are done putting this all together (or if you are looking at the attached source files) you'll see something like this:

A web page demonstrating membership with ASP.NET AJAX An error returned by ASP.NET AJAX to a custom function

Here is the source code for the above example: Membership With ASP.NET AJAX - Source Files

  • Feb 21 2008 - 12:06:21 PM stewsterl

    What is the point of using this method if a full post back and page refresh occurs?

  • Mar 21 2008 - 08:13:22 PM Timothy Khouri

    That's a great question. There are a few nominal benefits that I could mention, for instance, the fact that if the enter a wrong password, you save some transfer in telling them so... but that's not the point.

    You don't "have" to do a full post back. If you're site was built with AJAX from the ground up, you'd likely have some dynamicaly loading AJAX panels kicking off after you log in. Doing simple things like this will get your feet wet in the AJAX world though.

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

People to Follow

Experts in the categories related to this article.

  • Jonathan Carter

Related Blogs

These are the most recent blog posts related to this article.

  • How to Handle "Side Content" in ASP.NET MVC
  • LINQ to SQL - Am I Hitting The Database?
  • ASP.NET MVC - Issue with CSS Class Name on ActionLinks
  • Site Updates, Bug Fixes and Syndication in .NET 3.5

Related Ads

SingingEels.com as of Aug 20 2008 - 08:56:35 PM - (0.203125)