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:
- Run the ASPNET_REGSQL.exe against your SQL database to include the membership tables, views and stored procedures.
- 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:
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"
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:
Here is the source code for the above example: Membership With ASP.NET AJAX - Source Files