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 Roles in Forms Authentication in ASP.Net 2.0

By Satheesh babu
Posted On Jan 10,2009
Article Rating:
Be first to rate
this article.
No of Comments: 3
Category: ASP.Net
Print this article.

Using Roles in Forms Authentication in ASP.Net 2.0

Introduction

Authentication is one of the essential parts of any asp.net application we develop. Using authentication, our site visitors can be restricted to access private contents anonymously. Forms Authentication is one of the authentication mechanisms that can be used to authenticate users. Forms Authentication is best suited for internet applications as we can use Windows authentication in intranet scenarios. Thus, ASP.Net included all necessary classes to implement forms authentication easily.

From 1.x days, the implementation of forms authentication in ASP.Net is not that much complicated. But the actual drawbacks are in those days ASP.Net itself does not have that many controls that aid in implementing forms authentication easily. Also, if we have role based forms authentication then we should go for our custom code for validating a resource access. With the introduction of 2.0 we have a handful of controls that helps in implementing role based forms authentication very easy with the primary support of Providers in ASP.Net 2.0.

 

Who process the FormsAuthentication?

Forms authentication is processed by a HTTP module called FormsAuthenticationModule which takes part in regular ASP.net page processing.

 

Login Controls and Providers

As I said earlier, ASP.Net 2.0 is packed with set of new controls called Login controls through which we can implement forms authentication with very less effort. This section will take us through on how best are these Login controls to use in our projects. By default, Login controls will use the default membership provider and role provider which will have their own database schema. So, it is not advisable to use this controls as it is because enterprise applications itself will have its own database schema and architecture. Solution for this problem is to develop our own custom provider or our own custom code that solves our application specific requirements. However, we can still use some of the login controls like LoginView, LoginName and LoginStatus in our applications. In this article, I will explain our subject matter with a custom implemented login form without using any login control on it. Also we will have a look on how to use some of the login controls effectively with role based forms authentication. Moving forward I will explain a sample scenario where we can use role based forms authentication and will use the same scenario throughout this article for easy understanding.

 

Sample Scenario

Consider we are creating a content management system where users can login and post their contents. The posted contents will be moderated by administrator of the site. Means, Administrator can either approve or reject the content posted by the user. The posted content can be viewed by anyone once it is approved by the admin. In this scenario we can have 2 roles defined namely Admin and Publishers. The sample application attached with this article uses the same scenario explained in this article.

 

Application Structure

Our application will have two folders called Admin and Publisher as shown in below figure (Figure 1 – Sample Application Solution). Admin folder will have all the ASPX pages that are put together to form the Admin module while the Publisher folder will have all the ASPX pages for Publisher module.

Figure 1 – Sample Application Solution

 

Configuring Forms Authentication

 As we all know this is done in Web.config by changing the value of <authentication> tag.

<authentication mode="Forms">

      <forms loginUrl="Login.aspx"

        name=".ASPXAUTH"    

        protection="All"></forms>

</authentication>

 

The default timeout for forms authentication is 30 minutes. It indicates that 30 minutes of inactivity on the application will cause timeout expiration and the user will be prompted to login page. Any hit to the site after login will reset this clock to 30 minutes again starting from that time. If we want override this setting then we can include this in the above <forms> tag. See MSDN for full list of attributes that can be specified in this tag.

After configuring forms authentication we need to configure authorization part of the Web.Config.

  <authorization>

      <allow users="*"/>

  </authorization>

The above setting says it will allow all the users because the posted content should be viewed by anyone as I said in the Scenario section. Next section will explain the configuration settings to restrict users accessing the pages in Admin and Publisher folders.

 

Controlling Access to Roles

This is done by <Location> tag in Web.Config file.

<location path="ADMIN">

    <system.web>

      <authorization>

        <allow roles="ADMIN"/>

        <deny users="*"/>

      </authorization>

    </system.web>

  </location>

  <location path="Publishers">

    <system.web>

      <authorization>

        <allow roles="PUBLISHER,ADMIN"/>

        <deny users="*"/>

      </authorization>

    </system.web>

  </location>

 

The above setting will restrict users trying to access the Admin section and Publisher section until they are part of that role and allow users who are already part of the roles.

 




Constructing Login Form

Construct a login form that has textbox for entering userid and password, a button for login with an optional Remember me checkbox. Refer below figure.

On Login button click do the following steps,

1.      Create Forms Authentication ticket,

Listing 1 – FormsAuthentication ticket syntax

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

                                   int version,

                                            string userName,

                                   DateTime CreationTime,

                                   DateTime Expiration,

                                   bool IsPersistent,

                                   string UserData,

                                   string CookiePath);

User’s role information can be specified in UserData in the above argument list.

2.      Encrypt the above created ticket through following method in FormsAuthentication class,

Listing 2 - Encrypt Ticket

string Encrypt(FormsAuthenticationTicket ticket);

It returns a string containing an encrypted forms-authentication ticket suitable for use in an HTTP cookie.

1.      Create the cookie with the encrypted.

2.      Add the created cookie to the response object.

The below code Listing 3 shows the implementation of the above steps.

Listing 3 - Login Event

protected void btnLogin_Click(object sender, EventArgs e)

    {

        User _user = new User();

        DBOperations dbo = new DBOperations();

        _user = dbo.CheckUser(txtUserid.Text);

 

        if (_user != null)

        {

            if (_user.Password == txtPassword.Text)

            {

                FormsAuthenticationTicket Authticket = new

                            FormsAuthenticationTicket(1,

                            txtUserid.Text,

                            DateTime.Now,

                            DateTime.Now.AddMinutes(30),

                            chkRememberMe.Checked,

                            _user.Role,

                            FormsAuthentication.FormsCookiePath);

               

                string hash = FormsAuthentication.

                              Encrypt(Authticket);

 

                HttpCookie Authcookie = new HttpCookie(

                 FormsAuthentication.FormsCookieName,hash);

                

                if (Authticket.IsPersistent)

                    Authcookie.Expires = Authticket.Expiration;

               

                Response.Cookies.Add(Authcookie);

 

                string returnUrl = Request.QueryString["ReturnUrl"];

                if (returnUrl == null)

                    returnUrl = "/";

               

                Response.Redirect(returnUrl);

            }

            else

            {

                lblMessage.Text = "Password does'nt match.";

            }

        }

        else

        {

            lblMessage.Text = "User not exists.";

        }

    }

 

Since the user information is stored as encrypted value in the cookie we need to construct the decrypted version of our credentials for every request and assign it to the Context object. This is done to make the user information available on the pages. The FormsAuthentication module will decrypt the forms authentication ticket in the cookie and make it available through the property HttpContext.Current.User.Identity. A new GenericPrincipal object should be constructed and assigned to the User property of Context object. This has to be done in Application_AuthenticateRequest event in Global.asax file. By default, there will be no Global.asax file added to our solution if you use visual studio 2005 so we need to add it explicitly through “Add new Item”.

 

Listing 4 - Application Authenticate Event

 

protected void Application_AuthenticateRequest(Object sender,EventArgs e)

    {

        if (HttpContext.Current.User != null)

        {

            if (HttpContext.Current.User.Identity.IsAuthenticated)

            {

                if (HttpContext.Current.User.Identity

                    is FormsIdentity)

                    {

                      FormsIdentity id = (FormsIdentity)

                      HttpContext.Current.User.Identity;

                      FormsAuthenticationTicket ticket = id.Ticket;

                      string userInfo = ticket.UserData;

                      string[] roles = userInfo.Split(',');

                      HttpContext.Current.User =

                                   new GenericPrincipal(id, roles);

                }

            }

        }

    }

 

We need to import System.Security.Principal namespace to the Global.asax file for the above code to work. Refer the below snippet.

Listing 5 - Import Namespace

<%@ Import Namespace="System.Security.Principal" %>

 

Checking User Role in Code

The following code snippet will help us to check if the logged in user is part of a role.

Listing 6 - Role Chech In Code

if (User.IsInRole("ADMIN"))

lblMessage.Text = TechnicalErrorMsg;

 

Refer the link in Reference section of this article to deal with some of the common problems we may face when implementing forms authentication with roles.

 

How to use the source code attached with this article?

Unzip code, open it with visual studio 2005 and hit F5 to run. The code uses database attached in APP_Data, so you need to change any setting in Web.Config. The database has already 2 user ids created, test1 for ADMIN role and test2 for Publisher role, passwords are same as userid. Download the code and understand it better.

 

Download

Download Sample

 

Reference

MSDN

Implementing Forms Authentication in ASP.Net 2.0

LoginView Controls with Roles in ASP.Net 2.0

FormsAuthentication.SignOut() does not reflect in LoginStatus and LoginName control

Redirecting user to NotAuthorized page when tried accessing a restricted resource

Adding Remember Me Option in Login Form for Forms Authentication

 

Conclusion

Thus we have learnt implementation of role based forms authentication in ASP.Net 2.0 with a real time example. Also this article provides some of the tips to use the login controls efficiently in role based forms authentication. Download the code packed with this article and see it in action.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Best and Simple Implementetion Ever Seen
I visit many webs but unable to understand the authentication prosess - but this article is best for begginers like me. But try to submit these king of article in vb.
Nice Article
This article is very helpful to understand how authentication works in the entire application
Remember Me
Hiii
i ve go through ur article nd the code in zip attached. it works fine except t remember me option.pls check it............