Click here to Skip to main content
15,938,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to implement role based form authentication but in the end cookie not contain roles though i have provided.

Login.aspx
C#
if (Login1.UserName == "user" && Login1.Password == "user")
       {
           string role = "admin,member";

           FormsAuthenticationTicket t = new FormsAuthenticationTicke(1,Login1.UserName,DateTime.Now, DateTime.Today, false, role,"/");
           string cookiester = FormsAuthentication.Encrypt(t);
           HttpCookie cookie = new HttpCookie      (FormsAuthentication.FormsCookieName,cookiester);
           Response.Cookies.Add(cookie);
           if (t.IsPersistent)
           {
               cookie.Expires = t.Expiration;
           }
           String strRedirect = Request["ReturnUrl"];
           if (strRedirect == null)
           {
               strRedirect = "Default.aspx";
               Response.Redirect(strRedirect);
           }

          if(HttpContext.Current.User.IsInRole("admin"))
          {

           Response.Redirect("Secure/Secure.aspx");
          }
          }
       }
     }

Here i am taking "user" and provideing him "admin" rights.
Only admin role can log in to the "Secure\Secure.aspx" as per my web config:

XML
<location path="Secure">
	<system.web>
		<authorization>
			<allow roles="admin" />
			<deny users="*" />
		</authorization>
	</system.web>
</location> 


My global.aspx contains:
C#
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie =Context.Request.Cookies,FormsAuthentication.FormsCookieName];
    if (authCookie != null) 
    {
        FormsAuthenticationTicket t = FormsAuthentication.Decrypt(authCookie.Value);
        string[] roles = t.UserData.Split(new Char[] { ',' });
        GenericPrincipal userPrincipal = 
new GenericPrincipal(new GenericIdentity    (t.Name), roles);
        Context.User = userPrincipal; 
        
    }
}



What is wrong in this code? Why i cant use "admin" roles in this?
Posted
Updated 26-Jun-12 7:07am
v3

Looks like something is missing. Could you please check with the following link and see if you could change some bits and pieces where you find the discrepancy. this article has a working solution so you should be able to get yours to work too.

Understanding and Implementing ASP.NET Custom Forms Authentication[^]

Let me know if it helps.
 
Share this answer
 
Comments
vicvis 27-Jun-12 8:25am    
Thanks for your help..but i am unable to figure out the problem.
can it be because of encryption??

Appreciate your help
Rahul Rajat Singh 27-Jun-12 8:37am    
I suggest you take a deep breath. get some fresh air and then start afresh. start by rethinking the solution and refer the article in context. You should be able to solve it. sometimes it just need fresh perspective to solve the problems.

P.S. check my other solution to get some pointers.
vicvis 27-Jun-12 9:15am    
Hope u r right but i tried all your point.I must be missing something really critical.And it is context.user as e.user is not coming as an option.

Well i will try in some other way.

Thanks
Posting a separate answer just to avoid clutter.

Here are some pointers

1. too much of information in cookie, try to reduce it.
2. check if you are sending only allowed characters in the cookie or not.
3. Use SetAuthCookie function to set the cookie instead of doing all manually.
4. The event you are handling and the article talks about are different, check on those lines.
5. do we need to set the context.user or e.user as per the article.

I suggest to put the User data in the cookie. Put the Role data in a session variable. get the user name from cookie and if found ok, get the roles from session. then do what the GenericPrincipal creation.
 
Share this answer
 
Comments
vicvis 27-Jun-12 12:26pm    
I figured that my Global.aspx was not been called.But now i have another problem.As global.aspx is called when application starts,so it do not find any roles(Its obvious as uptil now user have not been to Login page).Now user is redirected to Login Page.After Filling credential as "admin",user is not redirected to Secure page because roles are derived in global.aspx which will now not be called as it is only called at begining of application.

I am bit confused!!shall i explicetely called "Application_AuthenticateRequest",then what will be the use of Global.aspx
Yet another answer to avoid clutter

I tried to modify your code and ran it. the following code is working fine at my end, check if you can get this to work at your end too or not.
C#
if (Login1.UserName == "user" && Login1.Password == "user")
        {
            string role = "admin,member";
           
           FormsAuthentication.SetAuthCookie(Login1.UserName, t.IsPersistent);
           Session["Roles"] = role;
            
           strRedirect = "Default.aspx";
            Response.Redirect(strRedirect);
           
           }
        }
      }

C#
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
dont use this event use this event/code instead.
C#
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                //let us extract the roles from our own custom cookie
                string roles = Session["Roles"] as string;

                //Let us set the Pricipal with our user specific details
                e.User = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(','));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}
 
Share this answer
 
v2
Comments
vicvis 5-Jul-12 15:28pm    
i got it solved now by making some changes but my application is working with application_authenticaterequest and not working with "FormsAuthentication_OnAuthenticate".

well it solved my purpose for time being...appreciate your help..
Saqlain Khalid 22-Feb-15 4:23am    
send code :/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900