Role Based Forms Authentication in ASP.NET 2.0
page 8 of 16
by Satheesh Babu
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 68539/ 172

Constructing Login Form

Construct a login form that has a textbox for entering user ID and password, and a button for login with an optional Remember me checkbox.

On Login button click do the following steps.

1.    Create Forms Authentication ticket.

Listing 4 – FormsAuthentication ticket syntax

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
int version,
string userName,
DateTime CreationTime,
DateTime Expiration,
bool IsPersistent, 
string UserData,
string CookiePath);

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

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

Listing 5 - Encrypt Ticket

string Encrypt(FormsAuthenticationTicket ticket);

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

5.    Create the cookie with the encrypted.

6.    Add the created cookie to the response object.

7.    The below code Listing 6 shows the implementation of the above steps.

Listing 6 - 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;
      string returnUrl = Request.QueryString["ReturnUrl"];
      if (returnUrl == null)
        returnUrl = "/";
      lblMessage.Text = "Password does'nt match.";
    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 7 - 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.

Listing 8 - Import Namespace

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

View Entire Article

User Comments

Title: it works at once   
Name: snopbear
Date: 2008-08-26 9:32:07 AM
When I log in with test1 or any of them, I get redirected to a HTTP Error 404 - Not Found page. Any ideas?
Title: Question   
Name: Jeff
Date: 2008-06-26 9:53:38 AM
When you log into the site with a user, go to their homepage, then click logout, hit the BACK button enough, it will get you into the home page without credentials.

Once you hit refresh it kicks you out and you have to login again.

This happens in IE6. It seems to work in Firefox right.
Title: Something is wrong   
Name: Mike
Date: 2008-06-25 10:16:43 AM
When I log in with test1 or any of them, I get redirected to a HTTP Error 404 - Not Found page. Any ideas?
Title: permissions and roles   
Name: tariq
Date: 2008-05-12 5:39:03 AM

I need to grant users with permissions depending on their roles. I have heard about Visual Guard .Net before I start testing, do you have any feedback about this tool?

thank you
Title: Thnx   
Name: Dhaval Patel
Date: 2008-05-02 11:04:11 AM
thanks buddy... it helped understanding it better.

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2023  |  Page Processed at 2023-10-02 8:25:36 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search