Solved

Forms authentication

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
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…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

685 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