CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Ajax Article » Using Authentication Services in ASP.NET AJAX for Forms Authentication   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

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

By Satheesh babu
Posted On Sep 29,2008
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 2
Print this article.
Category: ASP.Net AJAX

Subscribe to our feed!

Using Authentication Services in ASP.NET AJAX for Forms Authentication

 

Authentication is one of the important modules in any website we develop, unless and until there is nothing private on the site or something we explicitly know as being unnecessary. To provide Forms Authentication in ASP.Net AJAX, there is a service called Authentication Service is packed with the ASP.Net AJAX framework. It is a webservice which helps in authenticating users against the authentication database in ASP.Net AJAX applications. This webservice is called through a javascript proxy which gets exposed to the client by the ASP.Net AJAX framework when forms authentication is enabled.

This proxy scripts are packed inside Sys.Services namespace which can be used to access the web service from client side to verify the user and to set the authentication cookie.


By default, when we enable the forms authentication we can authenticate the user against the server with a default web service packed with ASP.Net AJAX. This default web service will authenticate the user using default provider and the default database aspnetdb. This means, by default, we need not write any code for authentication. Obviously, for a successful authentication the user should be added as a member in provide database. Moving forward, we will see how to use this authentication service to authenticate a user using the default provider.

 

Before moving to actual implementation, it will be good if have some rudimentary knowledge about the Authentication service in ASP.Net AJAX. As I said previously, the authentication service uses the existing provider model. Hence, it will be easy to migrate an existing asp.net application that uses login controls and providers. By default, this authentication service will also create an ASPXAUTH cookie on successful authentication, like the existing asp.net authentication infrastructure. So, whatever is possible with the existing asp.net authentication infrastructure is also possible with ASP.Net AJAX infrastructure with the support of client side proxy classes in Sys.Service namespace. For example, denying access to folders using location tag in web.config, etc.

 

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/she 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(MasterPage will be better) instead of redirecting to login page. Henceforth, we can enable protected resources only after authentication by showing some default items on the page which doesn’t require authentication. Also, 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 application that uses authentication service for providing forms authentication. In this article, we will use the default 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.

 



ASP.Net Hosting

Recent Articles

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. This webservice will in turn use the membership provider and the user is 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. Since, we are enabling/disabling controls in JavaScript it is advisable to check whether the user is authenticated before performing any protected server side operation which requires authentication.

 

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;

     }

 

On Logout completed callback, we can now disable the elements that requires authentication.

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 calls.

 

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 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 CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments
    How to work?
    Sorry, i'm a junior. I have question, I don't know how "Sys.Services.AuthenticationService.login(username, password, false,null, null, onLoginCallCompleted, null, username)" function execute. It mean, what is its authority for decision return value is True or False in "onLoginCallCompleted" function. Please help me. Thanks alot
    Force Login without UserName and Password
    hello there,
    i would like to know if there is a way to force login
    without supliy username and password?
    (in javascript)
    like to write e.autenticate = true;

    please help.
    thanks, gady.