Wednesday 20 July 2011

How to Add Errors to a LoginControl with ASP.NET and C#


In this tutorial we will demonstrate how to customize ASP.NET's Login Control to display detailed errors for our users.

Adding the Login Control
At this point in the tutorial I have created a new ASP.NET Empty Web Site in Microsoft Visual Web Developer and have added in a blank Web Form named Default.aspx. To add the login control, open up the Default.aspx page in Design mode and:
  1. Expand the Login tab in your toolbox.
  2. Drag and drop a Login Control onto the Web Form.
Adding Error Messages
At this point, we want to add some specific error messages to this control in the event that a login attempt fails. To do this:
  1. Right click the Login Control and select Properties.
  2. In the Properties window click the Events icon.
  3. SS1.jpg
  4. Double click the LoginError event to begin editing that method.

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

This method will run every time our Login Control fails to log in successfully. Here we need to determine what is causing the error. First, at the top of the class add in the following using statement:

using System.Web.Security;

This will allow us to use the Membership class which we will need to get data from our user that is attempting to login. Next, we need to add in the code to display the error messages. Add the following code to the LoginError event method:

MembershipUser currentUser = Membership.GetUser(Login1.UserName);

if (currentUser == null)
{
    //The GetUser method could not find a user with the given name. 
    //This indicates that the username entered does not exist.
    Login1.FailureText = "Invalid Username. Please try again.";
}
else
{
    //Check to see if the error occurred because they are not approved.
    if (!currentUser.IsApproved)
        Login1.FailureText = "Your account has not yet been approved by an administrator.";
    //Check to see if they are currently locked out.
    else if (currentUser.IsLockedOut)
        Login1.FailureText = "You have been locked out, please try again in 10 minutes.";
    //If none of these conditions have been met, the password is incorrect.
    else
        Login1.FailureText = "Invalid Password. Please try again.";
}

Let's go over this code line by line:

MembershipUser currentUser = Membership.GetUser(Login1.UserName);
This attempts to get the user with the current username in the Login Control from the database. If a user is found, the currentUser is populated with the user's information.
if (currentUser == null)
This simply checks to see if we found a user in the database with the given username. If this is null, that means that no user exists in our database with that name. The else statement to this corresponds to the case that the username entered was found.
Login1.FailureText = "Invalid Username. Please try again.";
This displays an error message for the case that the user does not exist.
if (!currentUser.IsApproved)
This checks to see if the user entered is not approved. By default when we create an account the user is approved.
Login1.FailureText = "Your account has not yet been approved by an administrator.";
This displays an error message for the case that the user is not approved.
else if (currentUser.IsLockedOut)
This checks to see if the user entered is locked out. To get locked out you must attempt to login with an invalid password 5 times within 10 minutes.
Login1.FailureText = "You have been locked out, please try again in 10 minutes.";
This displays an error message for the case that the user is locked out. By default, if a user is locked out their account is locked until an administrator unlocks it. However, most websites implement a time period for them to be locked out.
Login1.FailureText = "Invalid Password. Please try again.";
This displays an error message for the case that the password was incorrect. If none of the other conditions were met, the last thing to check would be the password.

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

Testing
To test these error messages appropriately, we must emulate the conditions that cause them. To do this, we will need to create an account:
  1. Click the ASP.NET Configuration icon in the Solution Explorer to open up the ASP.NET Website Administration Tool.
  2. In the ASP.NET Website Administration Tool click the Security tab.
  3. Under the Users header click the Select authentication type link.
  4. Select From the internet and click Done.
  5. Under the Users header click the Create Users link.
  6. Create a new user and click Done.
  7. Close the ASP.Net Website Administration Tool.
Next we are going to test all four of these cases to make sure that the correct error message is being displayed. To test all of these:
  1. Load up the website.
  2. Attempt to login with a fake username and password that you did not create. Notice the error message tells you that your username is invalid.
  3. Next, attempt to login with the username you created but use an incorrect password. Notice the error message tells you that your password is invalid.
  4. Close the website.
  5. In the Database Explorer, expand the ASPNETDB.mdf database.
  6. Expand the Tables folder.
  7. SS2.jpg
  8. Right click on the aspnet_Membership table and select Show Table Data.
  9. Under the IsApproved column corresponding with your username, change the value to 'False'.
  10. Save the table.
  11. Load up the website.
  12. Attempt to login with the correct username and password. Notice the error message tells you that your account has not been approved by an administrator.
  13. Close the website.
  14. Right click on the aspnet_Membership table and select Show Table Data.
  15. Under the IsApproved column corresponding with your username, change the value back to 'True'.
  16. Save the table.
  17. Load up the website.
  18. Attempt to login with your username and an incorrect password at least 6 times within 10 minutes. Notice the error message now tells you that you are locked out.

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

The Default.aspx source looks like this:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Login ID="Login1" runat="server" onloginerror="Login1_LoginError">
        </asp:Login>
    </div>
    </form>
</body>

The Default.aspx.cs code behind looks like this:
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Login1_LoginError(object sender, EventArgs e)
    {
        MembershipUser currentUser = Membership.GetUser(Login1.UserName);

        if (currentUser == null)
        {
            //The GetUser method could not find a user with the given name. 
            //This indicates that the username entered does not exist.
            Login1.FailureText = "Invalid Username. Please try again.";
        }
        else
        {
            //Check to see if the error occurred because they are not approved.
            if (!currentUser.IsApproved)
                Login1.FailureText = "Your account has not yet been approved by an administrator.";
            //Check to see if they are currently locked out.
            else if (currentUser.IsLockedOut)
                Login1.FailureText = "You have been locked out, please try again in 10 minutes.";
            //If none of these conditions have been met, the password is incorrect.
            else
                Login1.FailureText = "Invalid Password. Please try again.";
        }
    }
}

No comments:

Post a Comment