This post contains some of the most frequently asked questions When using the Login control:
1- how to redirect users to different pages based on their roles ?
This can be done by handling the LoggedIn event of the Login control like this:
protected void Login1_LoggedIn(object sender, EventArgs e) {
// if there is no returnUrl in the query string , we redirect based on user role
if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
// please don't use User.IsInRole here , because it will not be populated yet at this stage.
if (Roles.IsUserInRole(Login1.UserName, "Admins"))
Response.Redirect("~/Admins/Default.aspx");
else if (Roles.IsUserInRole(Login1.UserName, "Editors"))
Response.Redirect("~/Editors/Default.aspx");
}
}
2- how to hide the login control when the user logged in ?
Sometimes, you may place the login control in the MasterPage so that the Anonymous users can see it on every page.In this case, you may need to hide the Login control after the user login to the site.This is easy task and can be accomplished without hiding the control from code behind or placing it in a Panel.You just need to set it’s VisibleWhenLoggedIn property to false.
You can also use the LoginView control to accomplish that :
4-How to use the login control with my existing users table ?
By default,Login control will use the membership provider to validate users credentials , but if you already have your custom users table , you can use the login control like this:
private bool UserLogin(string userName, string password)
{
// read the coonection string from web.config
string conString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
{
//' declare the command that will be used to execute the select statement
SqlCommand com = new SqlCommand("SELECT UserName FROM Users WHERE UserName = @UserName AND Password = @Password", con);
// set the username and password parameters
com.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = userName;
com.Parameters.Add("@Password", SqlDbType.NVarChar).Value = password;
con.Open();
//' execute the select statment
string result =Convert.ToString( com.ExecuteScalar());
//' check the result
if (string.IsNullOrEmpty(result))
{
//invalid user/password , return flase
return false;
}
else
{
// valid login
return true;
}
}
}
5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
If you are using ASP.NET 2.0 , You can use the CSS friendly control adapters , check this link.
For Those who are using ASP.NET 4.0, you can prevent the Login control from wrapping itself with the html table by setting it's RenderOuterTable property to false.You can then go a further step and customize it's LayoutTemplate and make it render as you like.
You can find an example on how to customize the Login control Layout by creating a new website (not empty website) in VS 2010 and open the login.aspx page which will contain a very cool example about that.I will post the example here:
6- I’m getting invalid login after i published my website , the user name and password was working locally , what’s the problem ?
One possible reason is the applicationName in membership configuration, check this link for more information.
7-After i published my website , I’m getting System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1' .. error ,what to do ?
Feature
CompatibleSchemaVersion
IsCurrentVersion
common
1
TRUE
health monitoring
1
TRUE
membership
1
TRUE
personalization
1
TRUE
profile
1
TRUE
role manager
1
TRUE
8-How to display the login in popup ?
This example which use the PopupControlExtendar control from the Ajax control toolkit.
You can also use the Dialog from jQuery UI controls.
9- How can i log the invalid login attempts ?
one way is to handle the LoginError event of the login control:
protected void Login1_LoginError(object sender, EventArgs e)
{
// here you can login the invalid attempts
string UserName = Login1.UserName;
string Password = Login1.Password;
// log the attempt
}
10-I specified my website users in the credential section in web.config , can i still use the login control ?
Yes you can , you just need to handle the login control authenticate event .
Assume you have this Credential section in web.config:
5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.
This will expand all the code so you can style it up however you like.
4-How to use the login control with my existing users table ?
You could also create a custom membership provider so that this works seamlessly with your login control:
Sure, that's another solution for working with custom tables.If you followed this way,there is no need to customize or write any code for the Login control , the control must work natively with no problems.
rtpHarry
5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.
This will expand all the code so you can style it up however you like.
The login control always create a table to wrap it's contents , so even you customized it's layout and used <div> , the control will add outer html table to the rendered markup.
Edit(March 8 , 2010):In ASP.NET 4, there are a lot of enahncments to controls rendering.For example,the login control is no longer wrap it's contents in an outer table like before.
5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.
This will expand all the code so you can style it up however you like.
The login control always create a table to wrap it's contents , so even you customized it's layout and used <div> , the control will add outer html table to the rendered markup.
Thanks, It was a great help. I have an extra question:
What database is used for storing the usernames and passwords and other datas and how can I use it for example to show the list of users? and can I change the database into my own?
Best regards
Khashayar
---------------------------------------------
Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
Excellent article! Is there a way of switching a site based upon a database setting so that only administrators can access a given site?
[Edit: I suppose that if accounts can be programmatically diabled and re-enabled, I could just switch the non-admin accounts on and off.]
Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
I didnt get what you were saying at all last night... not sure I do now hehe, do you mean a lock down mode that would shut out all normal users?
I need to be able to block non-admins from using the site by an administrator making a change within the database and not by changing the web.config in the users folder. Conversely when the lock-out period is over, the administrator needs to be be able to
allow normal user access to resume just by means of an administrator option. The site administrators are quite non-technical and hence changing any of the sub-directory web.configs is not an option.
Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
I need to be able to block non-admins from using the site by an administrator making a change within the database and not by changing the web.config in the users folde
One solution is to Handle the AuthenticateRequst event in global.asax file and check the user role :
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// if the current requested url is not the login page
// and if someFlagInDatabase is true
if (!IsLoginPage && someFlagInDatabase == true)
if (! Roles.IsUserInRole("Administrators"))
{
Context.RewritePath("~/SiteIsCurrentlyUnAvailable.asxp");
}
}
protected string LoginUrl
{
get { return "~/Login.aspx"; }
}
// return true if the current page is the Login Page .
private bool IsLoginPage
{
get
{
return VirtualPathUtility.GetFileName(Request.Path).ToLower() ==
VirtualPathUtility.GetFileName(LoginUrl.ToLower());
}
}
Where "someFlagInDatabase" is the value that decide whether the site will be available just for admins.
anas
All-Star
73649 Points
7914 Posts
Moderator
Login control FAQ :
Mar 27, 2009 04:31 PM|LINK
This post contains some of the most frequently asked questions When using the Login control:
1- how to redirect users to different pages based on their roles ?
This can be done by handling the LoggedIn event of the Login control like this:
protected void Login1_LoggedIn(object sender, EventArgs e) { // if there is no returnUrl in the query string , we redirect based on user role if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { // please don't use User.IsInRole here , because it will not be populated yet at this stage. if (Roles.IsUserInRole(Login1.UserName, "Admins")) Response.Redirect("~/Admins/Default.aspx"); else if (Roles.IsUserInRole(Login1.UserName, "Editors")) Response.Redirect("~/Editors/Default.aspx"); } }2- how to hide the login control when the user logged in ?
Sometimes, you may place the login control in the MasterPage so that the Anonymous users can see it on every page.In this case, you may need to hide the Login control after the user login to the site.This is easy task and can be accomplished without hiding the control from code behind or placing it in a Panel.You just need to set it’s VisibleWhenLoggedIn property to false.
You can also use the LoginView control to accomplish that :
<asp:LoginView ID="LoginView1" runat="server"> <AnonymousTemplate> <asp:Login ID="Login1" runat="server"> </asp:Login> </AnonymousTemplate> </asp:LoginView>3-How to hide “remember me next time” checkbox from the login control ?
You may need to prevent the users from checking “remember me next time” checkbox to prevent crating a persistent authentication cookie.
To do that , you just need to set it’s DisplayRememberMe property to “false” and then you need to set it’s RememberMeSet property.
If you want to force the website to remember the users , you set the RememberMeSet property to true, else you set it to false.
<asp:Login ID="Login1" runat="server" DisplayRememberMe="false" RememberMeSet="false" …
4-How to use the login control with my existing users table ?
By default,Login control will use the membership provider to validate users credentials , but if you already have your custom users table , you can use the login control like this:
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e) { string userName = Login1.UserName; string password = Login1.Password; bool result = UserLogin(userName, password); if ((result)) { e.Authenticated = true; } else { e.Authenticated = false; } }private bool UserLogin(string userName, string password) { // read the coonection string from web.config string conString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString; using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString)) { //' declare the command that will be used to execute the select statement SqlCommand com = new SqlCommand("SELECT UserName FROM Users WHERE UserName = @UserName AND Password = @Password", con); // set the username and password parameters com.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = userName; com.Parameters.Add("@Password", SqlDbType.NVarChar).Value = password; con.Open(); //' execute the select statment string result =Convert.ToString( com.ExecuteScalar()); //' check the result if (string.IsNullOrEmpty(result)) { //invalid user/password , return flase return false; } else { // valid login return true; } } }5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
If you are using ASP.NET 2.0 , You can use the CSS friendly control adapters , check this link.
For Those who are using ASP.NET 4.0, you can prevent the Login control from wrapping itself with the html table by setting it's RenderOuterTable property to false.You can then go a further step and customize it's LayoutTemplate and make it render as you like.
You can find an example on how to customize the Login control Layout by creating a new website (not empty website) in VS 2010 and open the login.aspx page which will contain a very cool example about that.I will post the example here:
<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false"> <LayoutTemplate> <span class="failureNotification"> <asp:Literal ID="FailureText" runat="server"></asp:Literal> </span> <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" ValidationGroup="LoginUserValidationGroup"/> <div class="accountInfo"> <fieldset class="login"> <legend>Account Information</legend> <p> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label> <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:CheckBox ID="RememberMe" runat="server"/> <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label> </p> </fieldset> <p class="submitButton"> <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"/> </p> </div> </LayoutTemplate> </asp:Login>6- I’m getting invalid login after i published my website , the user name and password was working locally , what’s the problem ?
One possible reason is the applicationName in membership configuration, check this link for more information.
7-After i published my website , I’m getting System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1' .. error ,what to do ?
8-How to display the login in popup ?
This example which use the PopupControlExtendar control from the Ajax control toolkit.
You can also use the Dialog from jQuery UI controls.
9- How can i log the invalid login attempts ?
one way is to handle the LoginError event of the login control:
protected void Login1_LoginError(object sender, EventArgs e) { // here you can login the invalid attempts string UserName = Login1.UserName; string Password = Login1.Password; // log the attempt }10-I specified my website users in the credential section in web.config , can i still use the login control ?
Yes you can , you just need to handle the login control authenticate event .
Assume you have this Credential section in web.config:
<authentication mode="Forms"> <forms> <credentials passwordFormat="Clear"> <user name="User1" password="****" /> <user name="User2" password="****" /> </credentials> </forms> </authentication>You can let the login control use the mentioned section like this:
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e) { string UserName = Login1.UserName; string Password = Login1.Password; if (FormsAuthentication.Authenticate(UserName, Password)) { e.Authenticated = true; } else { e.Authenticated = false; } }Note: FormsAuthentication.Authenticate method will automatically check users against the credential section.
11- I'm not using FormsAuthenticaiton, instead I'm using the session object to secure my website , can i still use the login control ?
Yes , you can use it , please read my post on how to do this.
Hope it helped.
rtpHarry
All-Star
56620 Points
8958 Posts
Re: Login control FAQ :
Mar 27, 2009 08:33 PM|LINK
Hey,
Great tips Anas, I have learned a few things in this post!
I just wanted to add a couple of notes:
4-How to use the login control with my existing users table ?
You could also create a custom membership provider so that this works seamlessly with your login control:
5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?
You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.
This will expand all the code so you can style it up however you like.
anas
All-Star
73649 Points
7914 Posts
Moderator
Re: Login control FAQ :
Mar 27, 2009 08:52 PM|LINK
Hi,
Sure, that's another solution for working with custom tables.If you followed this way,there is no need to customize or write any code for the Login control , the control must work natively with no problems.
The login control always create a table to wrap it's contents , so even you customized it's layout and used <div> , the control will add outer html table to the rendered markup.
Edit(March 8 , 2010):In ASP.NET 4, there are a lot of enahncments to controls rendering.For example,the login control is no longer wrap it's contents in an outer table like before.
Thanks
rtpHarry
All-Star
56620 Points
8958 Posts
Re: Login control FAQ :
Mar 27, 2009 10:16 PM|LINK
Good point!
khparhami
Member
447 Points
194 Posts
Re: Login control FAQ :
May 16, 2009 07:21 AM|LINK
Thanks, It was a great help. I have an extra question:
What database is used for storing the usernames and passwords and other datas and how can I use it for example to show the list of users? and can I change the database into my own?
Khashayar
---------------------------------------------
Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
rtpHarry
All-Star
56620 Points
8958 Posts
Re: Login control FAQ :
May 19, 2009 10:56 PM|LINK
By default it uses the built in asp.net membership, roles, authentication, authorisation technologies.
Yeah you can write your own providers which plugin to the standard api and then let you use your own database
TATWORTH
All-Star
72415 Points
14017 Posts
MVP
Re: Login control FAQ :
May 22, 2009 07:33 PM|LINK
Anas
Excellent article! Is there a way of switching a site based upon a database setting so that only administrators can access a given site?
[Edit: I suppose that if accounts can be programmatically diabled and re-enabled, I could just switch the non-admin accounts on and off.]
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
rtpHarry
All-Star
56620 Points
8958 Posts
Re: Login control FAQ :
May 23, 2009 08:00 AM|LINK
I didnt get what you were saying at all last night... not sure I do now hehe, do you mean a lock down mode that would shut out all normal users?
TATWORTH
All-Star
72415 Points
14017 Posts
MVP
Re: Login control FAQ :
May 23, 2009 09:37 PM|LINK
I need to be able to block non-admins from using the site by an administrator making a change within the database and not by changing the web.config in the users folder. Conversely when the lock-out period is over, the administrator needs to be be able to allow normal user access to resume just by means of an administrator option. The site administrators are quite non-technical and hence changing any of the sub-directory web.configs is not an option.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
anas
All-Star
73649 Points
7914 Posts
Moderator
Re: Login control FAQ :
May 24, 2009 04:02 AM|LINK
Hi Mr TATWORTH,
One solution is to Handle the AuthenticateRequst event in global.asax file and check the user role :
protected void Application_AuthenticateRequest(object sender, EventArgs e) { // if the current requested url is not the login page // and if someFlagInDatabase is true if (!IsLoginPage && someFlagInDatabase == true) if (! Roles.IsUserInRole("Administrators")) { Context.RewritePath("~/SiteIsCurrentlyUnAvailable.asxp"); } } protected string LoginUrl { get { return "~/Login.aspx"; } } // return true if the current page is the Login Page . private bool IsLoginPage { get { return VirtualPathUtility.GetFileName(Request.Path).ToLower() == VirtualPathUtility.GetFileName(LoginUrl.ToLower()); } }Where "someFlagInDatabase" is the value that decide whether the site will be available just for admins.