Link to home
Start Free TrialLog in
Avatar of claracruz
claracruz

asked on

Forms authentication

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

Avatar of DreamMaster
DreamMaster

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

Regards,
Max.
ASKER CERTIFIED SOLUTION
Avatar of DreamMaster
DreamMaster

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of claracruz

ASKER

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.
You could use the Trim function to remove unwanted trailing or leading spaces.

Regards,
Max.
Glad to have been helpfull :)

Regards,
Max.