Solved

Forms authentication

Posted on 2006-07-04
5
336 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
  • 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
A short film showing how OnPage and Connectwise integration works.
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.

929 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now