views:

854

answers:

2

I'm trying to figure out how to implement an AJAX login for a ASP.NET 2.0 site with Jquery. I already have a implemented other simple Jquery AJAX application on the site, but I'm unsure how to convert over the standard login control to POST via AJAX. Should I expose the login.aspx page methods? Any help would be great.

+3  A: 

Here are some ideas on how this can be implemented. This is not full code, but it should be enough to get you started on the right track.

You need to create your own login form fields for username/password.

Create an ASMX or WCF WebService for authentication with a method similar to this:

[WebMethod]
public string AuthenticateUser(string username, string password)
{
    string result = "Invalid Username or Password";
    if(Membership.ValidateUser(userName, password))
    {
     FormsAuthentication.SetAuthCookie(u.UserName, false);
        result = "successful";
    }
    return result;
}

Then from your login button's click event you can use jQuery ajax to post the username/password to the webservice:

$.ajax({
  type: "POST",
  url: "WebService.asmx/AuthenticateUser",
  data: "{username:"+$('#txtUsername').val()+",password:"+$('#txtPassword').val()+"}",
  success: function(result) {
     alert(result);
    //if(result=='successful')
   // redirectUser to the home page
  }
});
Jose Basilio
Sweet. That helps a lot. Here's another question. Is there any way to store information in session from the webservice?
GreenEggs
Yes, just enable session in the WebMethod Attribute. [WebMethod(EnableSession = true)] and your HTTPContext's session will be available.
Jose Basilio
Awesome! That helps a ton!!! Thanks!
GreenEggs
Also take a look at the Sys.Services.AuthenticationService javascript proxy class that can be used for client-side authentication - http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Services/AuthenticationServiceClass/default.aspx
Russ Cam
A: 

Should this work in .net2 Why am I having problems with it?