Solved

Forms authentication

Posted on 2006-07-04
5
340 Views
Last Modified: 2012-06-27
Hello experts,

I have a weird problem, I don't know what am missing.

I log a user in no problem doing the following;-

 protected void Button2_Click1(object sender, EventArgs e)
    {
       
        CustomerLogin = new FixedAuctions.AuctionsDB();
        StringBuilder sbUserData = new StringBuilder();

       
        DataSet ds = CustomerLogin.CustomSelectLogin2(txtUsername2.Text, txtPassword2.Text);
        if (ds.Tables[0].Rows.Count == 1)
        {
           
            sbUserData.Append(ds.Tables[0].Rows[0]["CUSTOMERROLE"].ToString());
            sbUserData.Append("|");
            sbUserData.Append(ds.Tables[0].Rows[0]["CUSTOMERTYPEID"].ToString());
                  Session["CUSTOMERROLE"] = ds.Tables[0].Rows[0]["CUSTOMERROLE"].ToString();
                  Session["CUSTOMERID"] = ds.Tables[0].Rows[0]["CUSTOMERID"].ToString();
                  Session["SALENUMBERID"] = ds.Tables[0].Rows[0]["SALENUMBERID"].ToString();
            Session["VENDORID"] = ds.Tables[0].Rows[0]["VENDORID"].ToString();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUsername2.Text, DateTime.Now, DateTime.Now.AddMinutes(5), false, sbUserData.ToString(), FormsAuthentication.FormsCookiePath);
           

            // Hash the cookie for transport
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie FPAUCTION = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Name of auth cookie hash); // Hashed ticket

            // Add the cookie to the list for outgoing response
            Response.Cookies.Add(FPAUCTION);


            // Redirect to requested URL, or homepage if no previous page requested
           string returnUrl = Request.QueryString["ReturnUrl"];
               if ((ds.Tables[0].Rows[0]["CUSTOMERROLE"].ToString() == "CSREGD")) || (ds.Tables[0].Rows[0]["CUSTOMERROLE"].ToString() == "CS"))
               {
               returnUrl = "~/cs_auctions";
               }
           if (ds.Tables[0].Rows[0]["CUSTOMERROLE"].ToString() == "EDREGD")
               {
               returnUrl = "~/ed_auctions";
               }
           if (returnUrl == null) returnUrl = "~/ed_auctions";
            // Don't call FormsAuthentication.RedirectFromLoginPage
            //if (returnUrl == null) returnUrl = "~/cs_auctions";, since it could
            // replace the authentication ticket (cookie) just added
            Response.Redirect(returnUrl);
           

        }
        else
        {
            lblMessage.Text = "Invalid Login Details, Please Try Again!";
        }


I assign roles e.t.c, and am doing the following in my Global.asax;-

 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)
                {
                    // Get Forms Identity From Current User
                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                    // Get Forms Ticket From Identity object
                    FormsAuthenticationTicket ticket = id.Ticket;
                    // Get the stored user-data, in this case, our roles
                    string userData = ticket.UserData;
                    string[] roles = userData.Split('|');
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
                }
            }
        }

In My page load event, I am doing the following;-

protected void loadPage(object sender, EventArgs e)
    {
      try
     {
      // if they haven't logged in this will fail and we can send them to
      // the login page
      FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
     }
     // whatever bad happened, let's just send them back to login page for now...
     catch(Exception ex )
     {
      Response.Redirect("Default.aspx"); // whatever your login page is
     }
   // is this an Administrator role?
   if (User.IsInRole("EDREGD"))
     {
      Response.Write("Welcome Big Admin!");
      // ok let's enumerate their roles for them...
      FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
      FormsAuthenticationTicket ticket = id.Ticket;
      string userData = ticket.UserData;
      string[] roles = userData.Split('|');
      foreach(string role in roles)
       {
         Response.Write("You are: " + role.ToString()+"<BR>");
       }
Response.Write ("You get to see the Admin link:<BR><A href=\"Admin/Adminstuff.aspx\">Admin Only</a>");
               }
     else
         {
                         // ok, they got in but we know they aren't an Administrator...
                         Response.Write("Ya got logged in, but you ain't an Administrator!");
                         FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                         FormsAuthenticationTicket ticket = id.Ticket;
                         string userData = ticket.UserData;
                         string[] roles = userData.Split('|');
                           foreach(string role in roles)
                              {
                               Response.Write("You are: " +role.ToString()+"<BR>");
                              }
      
             
            }
            }

The problem is that on my page load event I am getting the following;-
Ya got logged in, but you ain't an Administrator!You are: EDREGD
You are: 1

which means that for role.ToString() wrtes the following;- "EDREGD" but is not recognised as being the user's role (User.IsInRole("EDREGD"))

What am I missing??


Many Thanks

0
Comment
Question by:claracruz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
5 Comments
 
LVL 19

Expert Comment

by:DreamMaster
ID: 17035782
Seems to me that EDREGD is not the full string, maybe there's a space in front or after EDREGD?

Regards,
Max.
0
 
LVL 19

Accepted Solution

by:
DreamMaster earned 500 total points
ID: 17035790
Maybe this link can shed some more light...

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.login.loggedin.aspx

Regards,
Max.
0
 
LVL 4

Author Comment

by:claracruz
ID: 17035881
Thanx Dream,

But am afraid I need more help.

If there are unwanted characters, how do I solve my problem.

Please give example code if you can.
0
 
LVL 19

Expert Comment

by:DreamMaster
ID: 17168456
You could use the Trim function to remove unwanted trailing or leading spaces.

Regards,
Max.
0
 
LVL 19

Expert Comment

by:DreamMaster
ID: 17249872
Glad to have been helpfull :)

Regards,
Max.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question