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?