Walkthrough: Creating a Web Site with Membership and User Login

A typical requirement for Web sites is to allow only some users (authenticated users) to see certain pages. In that case, it is typical for the Web site to provide a way for users to log in and be authenticated, and to hide information from anonymous users (users who are not logged in).

Note

If you create a web application in Visual Studio using a Web project template, the template includes pages that implement basic login functionality using login controls and ASP.NET membership. However, the template does not include all the functionality that is described in this walkthrough. If the template does not include the functionality you want, or if you prefer to create the membership system yourself, you can use the same ASP.NET controls that are in the template to create custom login and membership pages.

This walkthrough shows you how to manually put together these ASP.NET controls and ASP.NET membership services to create an application that authenticates users and that hides information from anonymous users. For information about how to use the Web site project templates, see Walkthrough: Creating an ASP.NET Web Site with Basic User Login.

Tasks illustrated in this walkthrough include the following:

  • Creating a Web site.

  • Creating a home page that is accessible to all users.

  • Creating a login page.

  • Creating a members-only page.

  • Configuring membership.

  • Adding new users (members).

  • Letting users change their password.

  • Letting users reset a forgotten password.

Prerequisites

In order to complete this walkthrough, you will need the following:

  • Visual Studio or Visual Web Developer Express installed on your computer.

  • SQL Server Express installed locally on your computer.

  • Access to an email server that can forward email messages. (The server does not have to be able to receive messages.) If you do not have access to an email server, you can run the procedures in this walkthrough, but you will not be able to use the password-recovery feature.

Creating the Web Site

To create custom user login pages, you will first create an empty Web site.

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio.

To create a Web site

  1. Start Visual Studio or Visual Web Developer Express.

  2. On the File menu, click New Web Site. (If you do not see this option, click New, and then click Web Site.)

    The New Web Site dialog box is displayed.

  3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site.

    You are selecting an Empty Web Site template because you will add membership and login capability by hand rather than using the features built into the other templates.

  4. In the Web location list box, select File System and enter the name of the folder where you want to keep the pages of the Web site. For example, enter the folder name C:\Websites\Membership and then click OK.

Visual Studio creates an empty Web site that contains only a Web.config file.

Creating the Home Page

You will first create the home page where all users of the Web site will start.

To create a home page

  1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.

    The Add New Item dialog box is displayed.

  2. If you do not see the Solution Explorer window, select the View menu and then click Solution Explorer.

  3. Select Web Form, accept the default name (Default.aspx), and then click Add.

  4. Switch to Design view and add text such as My Home Page.

  5. In the Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1.

Creating the Login Page

As part of your Web site, you must establish the user's identity (authenticate the user) so that the Web site can perform actions based on who the user is, such as showing or hiding information. To get the user's identity, you must have the user log in. Therefore, your Web site must include a login page.

To create a login page

  1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.

  2. Select Web Form, change the default name to Login.aspx, and then click Add.

    Note

    For this walkthrough, the page must be named Login.aspx. By default, ASP.NET authentication is configured to work with a page that has this name. (Although you will not do so in this walkthrough, you can change the default login page in the Web.config file.)

  3. In the Login.aspx page, switch to Design view.

  4. Add text such as Login Page to the page and again use Block Format to format the title as Heading 1.

  5. Press ENTER to create a new paragraph.

  6. From the Login group of the Toolbox, drag a Login control to the new paragraph.

    The Login control is a single control that will prompt the user for credentials and validate them. If you want, you can use the Auto Format link on the smart tag panel to apply formatting to the Login control.

Displaying Detailed Login Errors

The Login control includes validation to help users enter correct information. For example, if a user skips the password, a validator control displays an asterisk (*) next to the Password text box. To provide more detail about errors in the page, you will add a ValidationSummary control.

To display detailed login errors

  1. From the Validation group of the Toolbox, drag a ValidationSummary control onto the Login.aspx page. Drop the ValidationSummary under the Login control.

  2. In the Properties window for the ValidationSummary control, set the ValidationGroup property to Login1, which is the ID of the Login control that you added previously.

    (If you do not see the Properties window, from the View Menu, click Properties Window.)

  3. Save the page and close it.

You can now test the login page.

To test the login page

  1. In Solution Explorer, right-click the Login.aspx page and select View in Browser.

  2. Without entering anything into the login control, click Log In.

    An asterisk is displayed next to the User Name box and next to the Password box, because you did not enter values for these values. In addition, the ValidationSummary control displays error messages that provide details about the errors on the page.

  3. Close the browser.

Displaying Information for Logged-In Users

The next step is to modify the home page to customize the display depending on whether the user is logged in. Anonymous users will see a generic message that invites them to log in. Logged-in users will see a message that welcomes them by their user name.

To customize the display for logged-in users

  1. Switch to or open the Default.aspx page and switch to Design view.

  2. From the Login group of the Toolbox, drag a LoginView control onto the page.

    The LoginView control is displayed with its AnonymousTemplate template open. This template allows you to define the content that users will see before they log in.

  3. Click the edit area of the LoginView control to activate editing.

  4. In the edit area of the LoginView control's AnonymousTemplate template, enter You are not logged in. Click the Login link to sign in..

    The following illustration shows the LoginView control edit area that contains the text.

    LoginView Control

    It might be easier to copy the text and paste it into the edit area or add the text as markup in Source view than entering the text directly into the edit area. The following example shows how the text appears in markup.

    <asp:LoginView ID="LoginView1" runat="server" >
          <AnonymousTemplate>
              You are not logged in. Click the Login link to sign in. 
           </AnonymousTemplate>  
    </asp:LoginView>
    
  5. In Design view, select the LoginView control, and then on the LoginView Tasks panel, in the Views list, click LoggedInTemplate. If you do not see the LoginView Tasks panel, right-click the heading of the LoginView control and then click Show Smart Tag.

    The LoggedInTemplate defines the content that will be displayed to users who have logged in.

  6. Click the edit area of the LoginView control to activate editing and then enter the following text: You are logged in. Welcome,

  7. Place the cursor in the edit area of the LoggedInTemplate after the text you just added. From the Login group of the Toolbox, double-click the LoginName control. The LoginName control displays the name of the user who is logged in.

  8. From the Login group of the Toolbox, drag a LoginStatus control into the page. The LoginStatus control displays a Login link when the user is not logged in. When the user is logged in, the control displays a Logout hyperlink.

  9. Save the page.

Creating the Members-Only Page

A typical task in many Web sites is to allow only logged-in users to view certain pages. Therefore, the next task for this walkthrough is to create a folder for members-only pages, add a page to it, and then create a rule that limits access to pages in the folder.

To add a new folder to the Web site

  1. In Solution Explorer, right-click the name of the Web site and then click New Folder.

  2. Name the folder MemberPages.

  3. In Solution Explorer, right-click the MemberPages folder and then click Add New Item.

  4. Add a new Web Forms page named Members.aspx.

  5. Click Add.

    Note

    Make sure that you create the page in the MemberPages folder.

  6. Switch to Design view and add text to the page, such as Welcome to the members-only page. The exact text is not important, as long as you will be able to recognize this page when you see it in the browser. Use the Block Format drop-down list to format the text as Heading 1.

You can now add a hyperlink to the home page that sends users to the members-only page. In a real application, you would probably put the members-only page link in the logged-in template of the LoginView control. That way, visitors to your site would not see the link until they are logged in. However, for this walkthrough, you will make the link available to all users so that you can see the effect of trying to view a members-only page without first logging in.

  1. Open or switch to open the Default.aspx page.

  2. From the Standard group of the Toolbox, drag a HyperLink control onto the page.

  3. In the Properties window for the HyperLink control, do the following:

    1. Set the Text property to Members-only page.

    2. Set the NavigateUrl property to ~/MemberPages/Members.aspx. This points to the page that you created previously.

  4. Save the page.

You can now test the hyperlink you just added to the home page.

  1. In Solution Explorer, right-click the Default.aspx page and then click View in Browser.

  2. Click Members-only page.

    The members-only page is displayed, because it is not protected yet. (Moreover, by default, ASP.NET uses Windows authentication, so it considers you logged in under your Windows credentials.)

  3. Close the browser.

Configuring Membership

The next step is to configure ASP.NET membership and set up users. To do this, you can use the Web Site Administration Tool, which provides a wizard-like interface for making configuration settings. When you complete the configuration, a SQL Server database named ASPNETDB.MDF is created in the App_Data folder of the project. The database contains membership information for this Web site.

For this walkthrough, you will define a single user.

To create a membership user

  1. On the Website menu, click ASP.NET Configuration.

  2. Select the Security tab, click the Use the security Setup Wizard to configure security step by step link, and then click Next.

    The wizard displays a page where you can select the authentication method that your Web site will use.

  3. Select the From the Internet option.

    This option specifies that your Web site will use ASP.NET forms authentication, which relies on the ASP.NET membership system. When you use forms authentication, users log in to the Web site by using the login page that you created earlier in this walkthrough. (The From a local area network option configures the Web site to use Windows authentication, which is practical if your site is accessed only by people who are on a corporate network. As noted earlier, this is the default setting for ASP.NET membership.)

  4. Click Next.

    The wizard indicates that the application is configured to use advanced provider settings. By default, membership information is stored in a Microsoft SQL Server database file in the App_Data folder of your Web site.

  5. Click Next.

  6. Clear the Enable roles for this Web site check box, and then click Next.

    The wizard displays a page where you can create new users.

  7. Enter information that defines a user of your Web site. Use the following values as guidelines. (You can use any values that you want, but be sure to note your entries. You will use these entries later in the walkthrough.)

    • User Name   Your name (without spaces), or a sample name.

    • Password   A password. A strong password is required (one that includes uppercase and lowercase letters, punctuation, and that is at least eight characters long).

    • E-mail   Your personal email address. If you have to reset your password, this email address will be used to send you a new password. Therefore, you need to enter a valid email address.

    • Security Question and Security Answer   Enter a question and answer that can be used later if you need to reset your password.

  8. Select the Active User check box.

  9. Click Create User.

    The wizard displays a confirmation page.

    Note

    Leave the Web Site Administration tool open.

Setting Up Access Rules for the Members Page

Earlier in the walkthrough, you created a folder named MemberPages and added a members-only page. In this part of the walkthrough, you will create a rule that makes sure that only logged-in users can access pages in that folder.

To set up access rules

  1. In the security wizard in the Web Site Administration Tool, click Next.

    The wizard displays the Add New Access Rules page.

  2. In the Add New Access Rule box, expand the node for your Web site.

  3. Select MemberPages, the folder that you created earlier.

  4. Under Rule applies to, select Anonymous Users.

  5. Under Permission, select Deny.

    The rule you are creating denies access to anonymous users — that is, users who have not logged in.

  6. Click Add This Rule.

    The new rule is displayed in the grid. When users request a page from the MemberPages folder, the rules are checked to determine whether the user is allowed access to the page.

  7. Click Finish.

You are now done with the wizard. The wizard closes and you are returned to the Security tab of the Web Site Administration Tool.

Testing the Members-Only Page

You can test the members-only page by accessing it as an anonymous user or as a logged-in user.

To test the members-only page

  1. In Visual Studio, switch to the Default.aspx page and press CTRL+F5 to run the Web site.

  2. When the Default.aspx page is displayed in the browser, do not log in. Instead, click the Members-only page link.

    The Login.aspx page is displayed, because access to the member’s page is denied for anonymous users.

  3. On the login page, enter the user name and password that you used earlier to create the user to log in.

    When you log in, the site redirects you to the members-only page, because you are no longer an anonymous user.

  4. Close the browser window.

Adding New Users

Earlier in the walkthrough, you created a user by using the Web Site Administration Tool. The Web Site Administration Tool is useful if you are working with a small, defined list of users, such as creating users for a small team. However, in many Web sites, users can register themselves. To support this feature, ASP.NET includes the CreateUserWizard control that performs the same task you performed earlier by using the Web Site Administration Tool.

Creating a Registration Page

In this part of the walkthrough, you will add a functionality that allows users to register on your Web site. You will start by creating a registration page.

To create a registration page

  1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.

  2. Add a new Web Form named Register.aspx and click Add.

    Note

    Make sure that you create the page in the root of the Web site, not in the MemberPages folder.

  3. In the Register.aspx page, switch to Design view and enter text such as Register into the page. In the Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1.

  4. From the Login group of the Toolbox, drag a CreateUserWizard control onto the page.

  5. In the Properties window for the CreateUserWizard control, set the ContinueDestinationPageUrl property to ~/Default.aspx.

    This configures the control so that when users click Continue after they create a user, they are returned to the home page.

  6. From the Standard group of the Toolbox, drag a HyperLink control onto the page.

  7. In the Properties window for the HyperLink control, do the following:

    • Set the Text property to Home.

    • Set the NavigateUrl property to ~/Default.aspx.

  8. Save and close the page.

You will now add a link that displays the registration page to both the home page and the Login page. For this walkthrough, assume that you want to display the registration link only to users who are not logged in.

  1. Switch to or open the Default.aspx page.

  2. Right-click the LoginView control that you added previously, and then click Show Smart Tag.

  3. In the LoginView Tasks panel, select AnonymousTemplate from the Views list in order to activate editing in the anonymous template.

  4. From the Standard group of the Toolbox, drag a HyperLink control into the anonymous template. It might be easier to put the cursor in the editing area and double-click the HyperLink control in the Toolbox.

  5. In the Properties window for the HyperLink control, do the following:

    1. Set the Text property to Register.

    2. Set the NavigateUrl property to Register.aspx.

  6. Switch to or open the Login.aspx page.

  7. From the Standard group of the Toolbox, drag a HyperLinkcontrol into the page.

  8. In the Properties window for the HyperLinkcontrol, do the following:

    1. Set the Text property to Register.

    2. Set the NavigateUrl property to Register.aspx.

    You can now test the registration process.

To test registration

  1. Switch to the Default.aspx page and press CTRL+F5 to run the Web site and display the Default.aspx page.

    Because you are not logged in, the Register link is displayed.

  2. Click the Register link. The registration page is displayed.

  3. In the boxes, enter a new user name, a strong password, an email address, and a security question and answer. (All the pieces of information are required.)

  4. Click Create User. A confirmation message is displayed.

  5. Click Continue.

    You are returned to the home page as a logged-in user. Note that the Login link has changed to Logout and that the information displayed in the Login control is from the LoggedInTemplate property, not from the AnonymousTemplate property.

  6. Click the Logout link.The page changes to display the information for anonymous users.

  7. Click the Login link.

  8. Enter the credentials for the user you just created.You are logged in as the new user.

  9. Close the browser window.

Letting Users Change Their Password

Users sometimes want to change their passwords, and it is often impractical to perform this task by hand. You can use another ASP.NET control to let users change passwords on their own. To change a password, users must know their existing password.

You will add a page where logged-in users can change their password.

To create a password-change page

  1. In Solution Explorer, right-click the MemberPages folder, click Add New Item, add a new Web Form, name it ChangePassword.aspx and then click Add.

    Make sure that you create the page in the MemberPages folder. You are putting the page in the MemberPages folder because only logged-in users can change their passwords.

  2. In the ChangePassword.aspx page, switch to Design view and enter text such as Change Password and format it using Heading 1.

  3. From the Login group of the Toolbox, drag a ChangePassword control onto the page.

  4. In the Properties window for the ChangePassword control, set the ContinueDestinationPageUrl property to ~/Default.aspx.

    This configures the control so that when users click Continue after they change a password, they are redirected to the home page.

  5. Save and close the page.

You can now add a link to the home page that displays the ChangePassword.aspx page. You will make the link available only to users who are logged in.

  1. Switch to or open the Default.aspx page.

  2. Right-click the LoginView control and then click Show Smart Tag.

  3. In the LoginView Tasks pane, in the Views list, click LoggedInTemplate.

    This switches the LoginView control to edit mode for the content that will be displayed to users who are logged in.

  4. From the Standard group of the Toolbox, drag a HyperLink control into the editing region.

  5. In the Properties window for the HyperLink control, do the following:

    1. Set the Text property to Change password.

    2. Set the NavigateUrl property to ~/MemberPages/ChangePassword.aspx.

Testing the Password-Change Page

You can now test the password-change process.

To test the password-change page

  1. Press CTRL+F5 to run the Web site.

  2. In the Default.aspx, page, click the Login link and log in as one of the users you have created.

    When you are finished, you are returned to the home page as a logged-in user.

  3. Click the Change password link.

  4. In the password-change page, enter the old password and a new password, and then click Change Password.

  5. Click Continue.

  6. On the home page, click Logout.

  7. Click Login.

  8. Log in with the new password.

  9. Close the browser.

Letting Users Reset Their Password

When users forget their password, the Web site can enable them to recover or reset their password. The password can be recovered (that is, sent to the user) if the password is not hashed.

When a password is hashed, the membership system does not store the actual password. Instead, the system processes the password using a one-way algorithm (a hashing algorithm) that produces a unique value for the password, and then stores this hash value. This algorithm can be repeated to test a user's password at login, but cannot be reversed to produce the actual password. This increases the security of the membership database, because getting access to the database does not mean that passwords are exposed.

By default, the membership provider stores the password as a hash value. Therefore, the password cannot be recovered. Instead, if a user has forgotten a password, the Web site must generate a new password and send it to the user in email. For your Web site to send email messages your computer must have access to a Simple Mail Transport Protocol (SMTP) server.

In this procedure, you will add a password-reset page to your Web site and configure the Web site to send users a new password by email. To reset a password, a user must provide a user name and must answer the security question that was provided when the user registered. The new password is sent to the email address that the user provided when registering.

To create the password-reset page

  1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.

  2. Add a new Web Form page, name it PasswordRecovery.aspx and click Add.

    Note

    Make sure that you create the page in the root of the Web site, not in the MemberPages folder.

  3. In the PasswordRecovery.aspx page, switch to Design view and enter text such as Forgot Password into the page and format it as Heading 1.

  4. From the Login group of the Toolbox, drag a PasswordRecovery control onto the page.

  5. Open or switch to the Login.aspx page and switch to Design view.

  6. From the Standard group of the Toolbox, drag a HyperLink control onto the page.

  7. Set the Text property to Forgot password and the NavigateUrl property to ~/PasswordRecovery.aspx.

Configuring the Web site to Use an SMTP Server

Next, you will configure your Web site to use an SMTP server. To configure the server correctly, you must have the setup information. If the server requires authentication, you will need the user name and password. For information about how to obtain this setup information, contact the system administrator. After you have determined how to access the SMTP server, you must configure your Web site to route email messages to that server. You can do so in the Web Site Administration Tool or by making an entry in your Web site's Web.config file, which contains a series of settings that determine how your application runs. The following procedure shows how to use the ASP.NET Web Site Administration Tool to perform this task.

To configure the Web site to use an SMTP server

  1. On the Website menu, click ASP.NET Configuration.

  2. In the Web Site Administration Tool, click the Application tab.

  3. Under SMTP Settings, click Configure SMTP email settings. The tool displays a page where you can configure email.

  4. Enter the information that the page prompts you for.

  5. Click Save, and in the confirmation page, click OK.

    The Web Site Administration Tool creates a Web.config file that has the settings that you have made in the mailSettings section.

  6. Close the browser window in which the Web Site Administration tool is displayed.

  7. Open the Web.config file.

  8. Under the system.net element and under the mailSettings element, verify your smtp and host settings.

    Note

    If your SMTP server requires a secure connection, you must set the enableSsl attribute to true. You do this in the network section of the smtp element in the Web.config file.

    The SMTP settings in the Web.config file will resemble the following example.

    <system.net>
      <mailSettings>
        <smtp from="joe@contoso.com">
            <network host="<server>" password="<password>"   
             userName="joe@contoso.com" enableSsl="true" />
        </smtp>
      </mailSettings>
    </system.net>
    
    Security noteSecurity Note

    To protect configuration information like the user name and password, you can have ASP.NET encrypt the portion of the Web.config file where the SMTP information is stored. For more information, see Encrypting Configuration Information Using Protected Configuration. In addition, by default ASP.NET sends the smtp server credentials in clear text and can be intercepted by programs that record network activity. For a production site, you should use the SSL (secure sockets layer) to encrypt sensitive information that is exchanged with the server.

Testing Password Reset

You can now test the process of resetting your password. You will then use the new password to log in.

To test the password-reset page

  1. Press CTRL+F5 to run the Web site.

  2. Click Login.

  3. In the Login page, click the Forgot password link. Enter your user name and then click Submit.

  4. Enter the answer to the security question and then click Submit.

  5. Wait for a few minutes and then check your email.

  6. Use the new password to log in.

Next Steps

This walkthrough has illustrated a simple but complete scenario for creating an application that prompts users for credentials, displays information to logged-in users, limits access to pages, and lets users reset a forgotten password.

You can create more sophisticated pages and applications by using the techniques and controls illustrated in the walkthrough. For example, you might want to do the following:

See Also

Concepts

Introduction to Membership