protected void ButtonLogin_Click(object sender, EventArgs e)
{
BLCustomer blCustomer = new BLCustomer();
Customer cust = blCustomer.LoginOK(TextBoxUsername.Text, TextBoxPassword.Text);
if (cust == null)
{
LabelError.ForeColor = Color.Red;
LabelError.Text = "Acces denied.";
}
else
{
//LabelError.ForeColor = Color.Green;
//LabelError.Text = "Acces granted.";
//Roles.AddUserToRole(TextBoxUsername.Text, "User");
//Roles.AddUserToRole(TextBoxUsername.Text, "Admin");
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
TextBoxUsername.Text, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
CheckBoxRememberMe.Checked, // "true" for a persistent user cookie
"Admin", // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
// Redirect to requested URL, or homepage if no previous page
// requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "Home.aspx";
// Don't call FormsAuthentication.RedirectFromLoginPage since it
// could
// replace the authentication ticket (cookie) we just added
Response.Redirect(returnUrl);
//FormsAuthentication.RedirectFromLoginPage(TextBoxUsername.Text,
// CheckBoxRememberMe.Checked);
}
}
This is the global.asax file:
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)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
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);
}
}
}
}
When I now go to Orders.aspx, I get redirected to Login.aspx. For the first time it's normal, because I haven't logged in yet but when fill in the credentials and I click on the login button, I stay at the login page and I'm not redirected to Orders.aspx.
you can redirect to unauthorized page by some code in GLOBAL.ASAX :
Public Sub Application_AuthorizeRequest(ByVal sender As Object, ByVal e As EventArgs)
If (sender.Request.Path.ToUpper().EndsWith("LOGIN.ASPX") And sender.Request.IsAuthenticated) Then
sender.Response.Redirect("~/Unauthorized.aspx")
End If
End Sub
WillemsJoren
Member
4 Points
10 Posts
Forms authentication with roles
Jan 31, 2013 10:17 AM|LINK
Hi
I have a webform called Orders.aspx which is in a separate folder called 'Users'. In this folder I have following web.config file:
<system.web> <authorization> <allow roles="Admin"/> <deny users="*" /> </authorization> </system.web>In my root I have following web.config file:
<configuration> <connectionStrings> <add name="jorendbConnectionString" connectionString="Data Source=JOREN-PC\SQLEXPRESS;Initial Catalog=jorendb;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.5"> <assemblies> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <httpRuntime targetFramework="4.5"/> <authentication mode="Forms"> <forms name="NTier" loginUrl="login.aspx" protection="All" timeout="60" path="/" /> </authentication> <roleManager enabled="true" /> <authorization> <deny users="?" /> </authorization> </system.web> </configuration>This is the code behind the login event:
protected void ButtonLogin_Click(object sender, EventArgs e) { BLCustomer blCustomer = new BLCustomer(); Customer cust = blCustomer.LoginOK(TextBoxUsername.Text, TextBoxPassword.Text); if (cust == null) { LabelError.ForeColor = Color.Red; LabelError.Text = "Acces denied."; } else { //LabelError.ForeColor = Color.Green; //LabelError.Text = "Acces granted."; //Roles.AddUserToRole(TextBoxUsername.Text, "User"); //Roles.AddUserToRole(TextBoxUsername.Text, "Admin"); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version TextBoxUsername.Text, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire CheckBoxRememberMe.Checked, // "true" for a persistent user cookie "Admin", // User-data, in this case the roles FormsAuthentication.FormsCookiePath); // Encrypt the cookie using the machine key for secure transport string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; // Add the cookie to the list for outgoing response Response.Cookies.Add(cookie); // Redirect to requested URL, or homepage if no previous page // requested string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) returnUrl = "Home.aspx"; // Don't call FormsAuthentication.RedirectFromLoginPage since it // could // replace the authentication ticket (cookie) we just added Response.Redirect(returnUrl); //FormsAuthentication.RedirectFromLoginPage(TextBoxUsername.Text, // CheckBoxRememberMe.Checked); } }This is the global.asax file:
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) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; 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); } } } }When I now go to Orders.aspx, I get redirected to Login.aspx. For the first time it's normal, because I haven't logged in yet but when fill in the credentials and I click on the login button, I stay at the login page and I'm not redirected to Orders.aspx.
Anyone an idea?
Thx
oned_gk
All-Star
31017 Points
6352 Posts
Re: Forms authentication with roles
Jan 31, 2013 11:11 AM|LINK
you can redirect to unauthorized page by some code in GLOBAL.ASAX :
Public Sub Application_AuthorizeRequest(ByVal sender As Object, ByVal e As EventArgs) If (sender.Request.Path.ToUpper().EndsWith("LOGIN.ASPX") And sender.Request.IsAuthenticated) Then sender.Response.Redirect("~/Unauthorized.aspx") End If End SubSorry for VB code