CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Custom Implemented Authentication Services in ASP.NET AJAX for Forms Authentication

By Satheesh babu
Posted On Oct 13,2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 2
Category: ASP.Net AJAX
Print this article.

Custom Implemented Authentication Services in ASP.NET AJAX for Forms Authentication

 

My previous article, Using Authentication Services in ASP.NET AJAX for Forms Authentication gave an introduction on authentication services in ASP.Net AJAX and discussed the implementation of authentication services using the default webservice. In real time, we can’t use the default webservice which uses the membership provider and membership database. It is because; we will have our own database schema where the user information has stored. To overcome this difficulty, we will develop our own webservice that authenticates the user against our own database instead of using default membership database.

 

For reference purpose, I have included some of the concepts that are explained in previous article in this article also.

 

Design Consideration for Forms Authentications in AJAX application

The main aim of having AJAX application is to prevent the page refresh for server communication which provides better user experience when compared to classic asp.net applications. In classic asp.net, we will normally have a separate login.aspx page to authenticate users. Means, whenever the user gives a request to access the private resource he will be redirected to login.aspx or the login page we provide in <Forms> tag in web.config. As I said earlier, the main idea behind the Ajax application is to prevent page refresh hence it will be better if we design our Ajax application to have the login box in every page. We can enable protected resources only after authentication by showing some default items on the page which doesn’t require authentication. We can still follow the classic asp.net style by having a separate login.aspx page if our application requires.

 

With this information, we will move ahead and implement a sample forms authentication using asp.net Ajax authentication service. In this article, we will construct our own custom webservice to authenticate the user.

 

Sample Application

We will develop a sample application for article hosting. We will have an article page with a sample article posted on it. The article content will be displayed and can be seen without authenticating. To post comment on the article, one should log in to see the comment panel which has textbox to post the comment.

 

Before Login,

 

After Logged in,

 

Steps

1.      Open Visual studio 2005. Click File> New Website.

2.      Select ASP.Net AJAX-Enabled Web Site. Type your website name.

 

Enabling Authentication Services

The below setting in Web.Config will enable authentication service for the AJAX application.

 

<system.web.extensions>

    <scripting>

      <webServices>

        <authenticationService enabled="true" />    

      </webServices>

    </scripting>

  </system.web.extensions>

 

When we include the above setting in Web.Config file, the client side proxy class for calling webservice will be automatically exposed in the client side by Asp.net Ajax.

 

Like classic asp.net application, we need to set the authentication mode to “Forms” for the forms authentication to work.

 

<authentication mode="Forms" />

 

You can also set the login URL if you use separate login page.

 

Constructing the custom Webservice

1.      Include a Webservice in the application from the solution explorer.(Right Click>Add New item > select WebService)

2.      The custom webservice should have 2 methods, Login and Logout.

[ScriptService]

[WebService]

public class AuthService : WebService

{

 

     [WebMethod]

     public bool Login(string userName, string password, bool createCookie)

     {

          //Custom Authentication code to verify against our database

     }

 

     [WebMethod]

     public void Logout()

     {

         

     }

}

As you see above the Webservice class should be decorated by [ScriptService] attribute.

3.      In this article, I have used membership provider to authenticate for easy understanding/implementation. You can use your own code instead.

  [WebMethod]

    public bool Login(string userName,

        string password, bool createPersistentCookie)

    {

        //Place code here.

        bool result = Membership.ValidateUser(userName, password);

        if (result)

        {

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

        }

        return result;

    }

 

    [WebMethod]

    public void Logout()

    {

        FormsAuthentication.SignOut();

    } 

In next sections, we will implement client part of the custom implemented forms authentication and call our custom web service.

 

Configuring ScriptManager for Custom WebService

To configure Authentication service to call custom webservice, we need to configure the authentication service section of ScriptManager.

 

<asp:ScriptManager ID="ScriptManager1" runat="server" >

  <AuthenticationService Path="CustomAuthService.asmx" />

</asp:ScriptManager>

 




Constructing Login box

Drag 2 textbox for Username and Password with a Button control for login click.

<table>

                    <tr>

                        <td style="width: 100px">

                        UserName

                        </td>

                        <td style="width: 100px">

                            <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>

                    </tr>

                    <tr>

                        <td style="width: 100px">

                        Password

                        </td>

                        <td style="width: 100px">

                            <asp:TextBox ID="txtPass" runat="server"></asp:TextBox></td>

                    </tr>

                    <tr>

                        <td style="width: 100px">

                        </td>

                        <td style="width: 100px">

                            <asp:Button ID="btnLogin" runat="server" OnClientClick="return OnLogin();" Text="Login" /></td>

                    </tr>

</table>

 

From JavaScript, we need to call the authentication web service for authentication. It is done by calling the webservice through the proxy method called login in AuthenticationService class which is packed in Sys.Service namespace using javascript.

 

The syntax of the login method is,

Sys.Services.AuthenticationService.login(userName, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext);

 

isPersistent – Specifes the cookie is persistent or non persistent.

 

customInfo - Reserved for future use. The default is null.

 

redirectUrl – Redirect URL for successful authentication. null specifies no redirection.

 

loginCompletedCallback – This callback javascript function will be called once the authentication service returns to client. It is called for both authentication failure and success.

 

failedCallback – This callback function will be called if there is any exception happened on the server while authenticating. Authentication failure will not call this callback method.

 

userContext – User context info we are passing for callback function.

 

When the method is called with argument values, it calls the webservice login method which will verify the credentials in the server against the database and set the auth cookie. The webservice will in turn use the membership provider and the users are checked against the default database in aspnetdb in App_Data folder.

 

  function OnLogin()

    {

    var username = $get("txtUserName");

    var password = $get("txtPass");       

    Sys.Services.AuthenticationService.login(username.value,

        password.value, false,null,null,onLoginCompleted,onLoginFailed,"User Context");

        return false;

    }

 

function onLoginFailed()

     {

     alert("Login failed due to some exception");

     }

 

     function onLoginCompleted()

     {

     loggedIn = Sys.Services.AuthenticationService.get_isLoggedIn();

     if(loggedIn)

     {

     $get("CommentsDIV").style.display ="block";

     $get("UserDetails").style.display ="block";

     $get("UserName").innerText = $get("txtUserName").value;

     $get("LoginDIV").style.display ="none";

     }

     else

     {

        alert("Login failed due to invalid credentials!!");

     }

     }

 

As you can see the above code, we can use the login completed callback function to enable/disable protected resources on the page. In our example, it is commenting panel and login box.

 

For logout, we can call the logout method of AuthenticationService class.

 

The syntax of this method is,

Sys.Services.AuthenticationService.logout(redirectUrl, logoutCompletedCallback, failedCallback, userContext);

 

logoutCompletedCallback & failedCallback are callback methods fore respective operations, as the name suggests.

 

We can have a hyperlink to call the logout method similar to below.

 

function SignOut()

     {

     Sys.Services.AuthenticationService.logout(null,onLogoutCompleted,null,null);

    return false;

     }

 

Before authenticating, we need to register the user or create users in aspnetdb database. Use CreateUserWizard from login controls to create new users easily. The aspnetdb database in App_Data folder will be automatically created for the first request given to the provider for creating new user. Once you create a new user, you can use the above authentication service for successful authentication.

 

Callback function

 The callback function that is used in login and logout method can have 3 arguments.

1.      Result à which gives the client side exception object that substitutes the server exception. To get exception message, etc.

2.      userContext à Usercontext info we passed during server method call.

3.      Method à Method that made the server call.

 

Hence the above callback method can be written as,

 

function onLoginFailed(Result, userContext, Method)

     {

     alert("Login failed due to exception: "+Result.get_message()+" on method "+ Method);        

     }

 

Downloads

Source Code

 

Conclusion

Thus we have understood the implementation of custom Authentication Service in ASP.Net AJAX. To make the forms authentication more reliable and to increase user experiences, we have decided to have the login box in every page instead of separate login page. Hence, I have kept the login box in bottom the aspx page. It will be good, if we move the login box inside a Master page to have the login box in every page and write our handling code in Jscript for enabling and disabling controls on the page.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Rreturning values from LOgin method
Is it possible to return more values in any other ref parameters from log in method. I want to return a string value
Thanks
Anil Madan
Thanks for the article
Hi,
Thanks for the article!