Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET
I was trying to implement role based form authentication but in the end cookie not contain roles though i have provided.
 
Login.aspx
 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:
 
<location path="Secure">
	<system.web>
		<authorization>
			<allow roles="admin" />
			<deny users="*" />
		</authorization>
	</system.web>
</location> 

 
My global.aspx contains:
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 26-Jun-12 7:56am
vicvis596
Edited 26-Jun-12 8:07am
Tim Corey90.6K
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
vicvis at 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 at 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 at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Comments
vicvis at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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.
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);
           
           }
        }
      }
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
dont use this event use this event/code instead.
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
            }
        }
    }
}
  Permalink  
v2
Comments
vicvis at 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..

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

  Print Answers RSS
0 OriginalGriff 7,903
1 Sergey Alexandrovich Kryukov 7,142
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,820


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 28 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100