Solved

Forms authentication

Posted on 2006-07-04
5
335 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
You could use the Trim function to remove unwanted trailing or leading spaces.

Regards,
Max.
0
 
LVL 19

Expert Comment

by:DreamMaster
Comment Utility
Glad to have been helpfull :)

Regards,
Max.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

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…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 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

11 Experts available now in Live!

Get 1:1 Help Now