ASP.NET User Management

Views: This article has been read 94966 times.
Abstract: This tutorial covers all major and most minor technologies of managing users and their roles in an ASP.NET Web application.

ASP.NET User Management

The ASP.NET Membership and Roles services provide built-in code (from the ASP.NET object model) that is used to manage users and their roles. This code is accessed through several ASP.NET Login controls and methods.

This section includes the following subsections:

  • Membership Service
  • Roles Service
  • Stored Procedures/Methods Execution and Order
  • aspnetdb Database
  • ASP.NET Web Site Administration Tool

Membership Service

The Membership class includes several ASP.NET Login controls and methods that are used to create, delete, modify, retrieve, and authenticate users. A provider named “AspNetSqlMembershipProvider” acts as an interface between the ASP.NET Membership service and the SQL Server database (aspnetdb). To make this work, the provider must be registered. This is done through a setting in the machine.config file, as shown in the following code.

<membership>
      <providers>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
      </providers>
</membership>

For more information on the machine.config file, see web.config Settings.

Membership Settings in IIS

The Membership provider settings can also be made in IIS. To do this, perform the following steps:

  1. In IIS, access the properties dialog box of Web application's virtual directory.
  2. In the properties dialog box, select the ASP.NET tab.
  3. Within “ASP.NET”, select the “Edit Configuration…” button.
  4. Within “ASP.NET Configuration Settings”, select the “Authentication” tab.
  5. Within “Authentication”, select the “Manage Providers…” button in the “Membership” section. (Note that you can also make changes to the Roles provider by selecting the “Manage Providers…” button in the “Roles” section.)
  6. In the “Provider Settings” you can make changes to the Membership settings.

ASP.NET Login Controls

The following is a list of ASP.NET Login controls and methods that can be used:

  • LoginView
  • LoginStatus
  • LoginName
  • ChangePassword
  • PasswordRecovery
  • CreateUserWizard
  • VerifyUser Method
  • CreateUser Method

LoginView Control

The LoginView control provides the login presentation layer and functional login code. The presentation layer includes login controls, logout button, and additional hyperlinks to create a user login and change and reset existing user’s password.

The LoginView automatically detects a user's authentication status and role. The LoginView provides two templates: AnonymousTemplate and LoggedInTemplate. If the visitor is not logged in, the AnonymousTemplate will display in the login section. This template contains the login controls to allow the user to log in and hyperlink to a potential create user Web page to allow the user to create a login or recover their password. When the user is logged in, the LoggedInTemplate is displayed. This template turns visibility of the login controls off, displays a welcome message with the visitor’s username, and provides a hyperlink to the a potential change password Web page to allow the user to change their password.

The LoginView creates html tags that are shown in the following code. For simplicity, the tags’ attributes and their settings have not been included.

<asp:LoginView ID="LoginView1" runat="server">
     <!—for simplicity, only tags used are shown -->
     <AnonymousTemplate>
          <asp:Login>
               <LoginButtonStyle />
               <TextBoxStyle />
               <LabelStyle /> 
               <TitleTextStyle />
               <CheckBoxStyle />
               <FailureTextStyle />
               <HyperLinkStyle />
          </asp:Login>
     </AnonymousTemplate>
     <!—for simplicity, only tags used are shown -->
     <LoggedInTemplate>
          <span id="login-welcome">Welcome</span>
          <span id="login-name">
               <asp:LoginName /> <br />
               <asp:Label></asp:Label>
          </span> 
          <span id="loginlinks"> 
          <asp:LoginStatus />
     </LoggedInTemplate>
</asp:LoginView>

The functional code that is connected to the LoginView control is part of the ASP.NET object model. After the user enters their badge number and password and selects "Log In", the Membership class's GetUser method is invoked, which checks the aspnetdb database to see if the login exists.

LoginStatus

The LoginStatus control displays the “Login” and “Logout” button, depending on whether or not the user is logged in or logged out. A “LogoutPageUrl” property, in this example, is set to redirect the current Web page the user is in to Default.aspx, as shown in the following code. The attributes of this control can be accessed through the properties explorer in design view.

<asp:LoginStatus ID="LoginStatus1" runat="server" CssClass="logout-buttons" LogoutPageUrl="Default.aspx" />

LoginName

The LoginName control displays the username of the currently logged on user. This control can be used throughout the application to display the username, as shown in the following code: Logged on username can also be accessed programmatically using User.Identity.Name.

Welcome <asp:LoginName ID="LoginName1" Runat="server" />

ChangePassword

The ChangePassword control allows the user to change their password. The new password is encrypted and saved in the aspnet_Users table. The length of the password (as default) must be a minimum of 7 and contain at least one non-alphanumeric character. These specifications can be changed in the web.config file.

To access this Web page, the user can select a “Change Password” hyperlink. This could be set to redirect the current Web page to a change password Web page. The user could then enter their old and new password and select the control's submit button. To access this control, the user is required to be logged in.

PasswordRecovery

The PasswordRecovery control is used to email the user’s existing password based on the user’s email address. This email address is saved in the aspnet_Membership table. This control could be located in a password recovery Web page.

To access this Web page, the user could select a reset password hyperlink. This could redirect the current Web page to password recovery Web page. The user would then enter their username in the PasswordRecovery control and select the submit button. The password is then emailed to the user.

CreateUserWizard

The CreateUserWizard control allows a user with an administrative role to create a login. The CreateUserWizard control provides a user interface for creating new user accounts. Similar to the Login control, after the user fills in the required fields and selects the submit button the Membership class's CreateUser method is invoked, which writes the login data to aspnetdb database.

VerifyUser Method

The VerifyUser method is invoked when a user enters their username and password in the login fields and selects the submit button. A postback ensues and the control attempts to authenticate the user's supplied credentials by calling the Membership class's VerifyUser(username, password) method. If the credentials provided are valid, an authentication ticket (a cookie saved to the user’s browser) is created for the user; otherwise, an error message is displayed in the LoginView control's interface.

CreateUser Method

The CreateUser method is invoked when a user with the administrative role enters user information and selects the submit button. The information is then saved to the aspnet_Users and aspnet_Membership tables. A UserId is automatically assigned to the user in aspnet_Users and is used as a foreign key in aspnet_Membership and aspnet_Roles. The password is encrypted (default setting) and saved in aspnet_Membership.

Roles Service

The Roles class includes methods that are used to create and delete roles, assign and remove roles from users, and determine what users belong to a role, and to what roles a user belongs. A provider named “AspNetSqlRoleProvider” acts as an interface between the ASP.NET Roles service and the SQL Server database (aspnetdb). To make this work, the provider must be registered. This is done through a setting in the machine.config file, as shown in the following code.

<roleManager>
      <providers>
        <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
</roleManager>

For more information on the machine.config file, see web.config Settings.

Roles Settings in IIS

The Roles provider settings can also be made in IIS. To do this, perform the following steps:

  1. In IIS, access the properties dialog box of  the Web application's virtual directory.
  2. In the properties dialog box, select the ASP.NET tab.
  3. Within “ASP.NET”, select the “Edit Configuration…” button.
  4. Within “ASP.NET Configuration Settings”, select the “Authentication” tab.
  5. Within “Authentication”, select the “Manage Providers…” button in the “Roles” section. (Note that you can also make changes to the Membership provider by selecting the “Manage Providers…” button in the Membership section.)
  6. In the “Provider Settings” you can make changes to the Roles settings.

Roles Methods

The following describes the methods a Web application can use:

AddUsersToRole Method

The AddUsersToRole method is used to assign roles to users. For example, a user could be selected from one combo box, and the role to be assigned from another combo box, and select a submit button to assign the role to the user. The following is the code that is executed in the code-behind page.

Roles.AddUsersToRole(newusers, RolesListBox.SelectedItem.Value)

RemoveUserFromRole Method

The RemoveUserFromRole method is used to remove roles from users. This could be done by first selecting the role in a roles combo box, which then would display all the users assigned to that role below the combo box. Each user could have a “Remove From Role” hyperlink, which when clicked, would remove the user from the role. The following is the code that is executed in the code-behind page.

Roles.RemoveUserFromRole(username, RolesListBox.SelectedItem.Value)

GetAllRoles Method

The GetAllRoles method is used to return all available roles. These roles are stored in the RoleName field of the aspnet_Roles table.

GetUsersInRole Method

The GetUsersInRole method is used to return all available users that are assigned to a selected role. These users are stored in the UserName field of the aspnet_Users table.

GetRolesForUser

The GetRolesForUser method is used to return a user’s roles when the user logs in successfully. These roles are stored in an array named rolesArray.

aspnetdb Database

User login information is stored in the aspnetdb database in the aspnet_Users, aspnet_Membership and aspnet_UsersInRoles tables. When a login is created, a UserId is automatically created, encrypted and stored in the aspnet_Users table. This encrypted UserId is used as a foreign key to link the user information in the aspnet_Membership and aspnet_UserInRoles tables. User passwords are encrypted and saved in the aspnet_Membership tables and user roles are saved in the aspnet_UsersInRoles table.

The following is a list of tables and their primary fields where user data is stored:

  • aspnet_Users (created encrypted UserId, username, last activity date, etc.)
  • aspnet_Membership (Encrypted password, security question and answer, email, etc.)
  • aspnet_UsersInRoles (users’ assigned roles)

ASP.NET Web Site Administration Tool

The ASP.NET Web Site Administration Tool can only be accessed through Visual Studio. It provides functions to manually (not programmatically) create new users, create and assign roles, and make settings to the application’s web.config file (e.g. authorization settings). This tool is accessed by first opening the Web application in Visual Studio and then selecting ASP.NET Configuration from the Website menu. This will launch the ASP.NET Web Site Administration Tool in a browser.

By Todd Paholsky