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.
 
Using RoleService for Role Based Forms Authentication in ASP.NET AJAX

By Satheesh Babu
Posted On May 07,2009
Article Rating:
Average Rating: 3.5
No of Ratings: 2
No of Comments: 0
Category: ASP.Net AJAX
Print this article.

Using RoleService for Role Based Forms Authentication in ASP.NET AJAX

 

In my previous article Using Authentication Services in ASP.NET AJAX for Forms Authentication we have understood how to use the authentication service to provide forms authentication in ajax applications. Most of the times, we will also have number of roles to provide different set of permissions to different users. The ASP.Net AJAX Extensions 1.0 released for ASP.Net 2.0 does not have an inbuilt service like authentication service that provides roles support. The next version of ASP.Net AJAX that is shipped for ASP.Net 3.5 added a new client service called RoleService to support role based authentication in ASP.Net AJAX application.

Read my previous article Using Authentication Services in ASP.NET AJAX for Forms Authentication to understand this article. We will be using the same example which we used in the previous article.

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. This application will have 2 roles,

1.      ADMIN

2.      Publisher

Users with ADMIN role can see an additional toolbox to perform admin activities while the publisher and authenticated users can post comments but cannot see the admin toolbox.

 

Before Login,

 

After Logged in,

Admin View

Publisher view

 

Moving forward, we will see how we can build this simple application with inbuilt authentication and role service.

 

Steps

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

2.      Select ASP.Net Web Site. Type your website name.

 

Enabling Authentication Services and RoleService

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

<system.web.extensions>

  <scripting>

   <webServices>

       <authenticationService enabled="true"/>

        <roleService enabled="true"/>

   </webServices>

</scripting>

</system.web.extensions>  

 

When we include the above setting in Web.Config file, the client side proxy class for calling authentication and role webservice will be automatically exposed in the client side by asp.net ajax. Also, enable the role manager in web.config file to fetch the role data from the database.

 

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 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 that is Sys.Service namespace from javascript.

 

Once the user is authenticated, we can use the role service to check the user’s role and enable the corresponding UI elements. To do this, we can use the Load() method of Sys.Services.RoleService to fetch the logged in user’s role and load into the client memory.

 

Syntax

Sys.Services.RoleService.load(loadCompletedCallback, failedCallback, userContext);

 

loadCompletedCallback

 The function that is called when the load operation has completed. The default is null.

 

failedCallback

 The function that is called if loading has failed. The default is null.

 

userContext

 User context information that is passed to the callback functions.

 

The below code will authenticate the user and enable the UI elements for the users with admin role.

 

  <script type="text/javascript">  

     var loggedIn;

     var roleProxy;  

 

    function pageLoad() {      

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

        if(loggedIn)

        {

            //Enable UI elements for logged users

        }

        else       

        {

            //disable UI elements

        }

        roleProxy = Sys.Services.RoleService; 

   

    }

  

    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(Result, userContext, Method)

     {

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

     }

     function onLoginCompleted(Result, userContext, Method)

     {    

         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";

         loadRoles();

         }

         else

         {

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

         }

     }

     function SignOut()

     {

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

         return false;

     }

     function onLogoutCompleted()

     {       

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

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

          alert("Logged Out!!!");

          return false;

     }

     function loadRoles() {

         roleProxy.load(fnLoadRolesComplete, fnLoadRolesFail, null);    

     }

     function fnLoadRolesComplete(result, userContext, methodName) {       

         if (roleProxy.isUserInRole("ADMIN")) {

//Enable UI controls for admins

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

         } else {

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

         }

     }

 

     function fnLoadRolesFail(error, userContext, methodName) {

         alert(error.get_message());

     }

</script>

 

In the above code,

LoginDIV - it is the div that contains the control to login.

CommentsDIV - it is the div that contains the control for commenting.

AdminPanel   - it is the div that contains the control for admins.

 

 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 which can be shown to all the user roles (Admin and Publisher). Once the user is successfully authenticated we need to load the roles of the user by calling the role service. Thus, we have called the role service from the onLoginCompleted callback function in the above code. Once the role for the authenticated user is loaded successfully we can enable the admin panel from fnLoadRolesComplete callback function.

 

Since, we are enabling/disabling controls in JavaScript, it is advisable to check whether the user is authenticated and user’s role before performing any protected server side operation. For example, if a page should be accessed only by an admin then it is important that you should check the user’s role in the page load.

 

public partial class Admin_Dashboard : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if(!User.IsInRole("ADMIN"))

        {

            Response.Redirect("NotAuthorized.aspx");

        }

    }

}

Alternatively, you can also use the location element to restrict access to a resource from web.config file.

 

Download the source attached with this article to understand it better.

 

How to use the sample application?

I have used default aspnetdb in App_Data folder to store user information. Use the page CreatUser.aspx to create new user, role and assign a role to user. So, create 2 roles ADMIN and Publisher. Also, create 2 new userids and associate the role with the users.

 

Downloads

Download Source 

Conclusion

Thus we have understood the implementation of Authentication Service and role service in ASP.Net AJAX to implement form based authentication. To make the forms authentication more reliable and to increase user experiences, we can have the login box on 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