Last week we began our discussion of website personalization with Visual Basic 2005. This week, we continue that discussion with an explanation of how to add roles to ASP.NET accounts. This article is excerpted from chapter 12 of the book Programming Visual Basic 2005, written by Jesse Liberty (O'Reilly, 2005; ISBN: 0596009496).
Contributed by O'Reilly Media Rating: / 17 November 22, 2006
Authentication is the process of identifying a user; authorization is the process of deciding which parts of your application that user can see and interact with. The forms-based security controls and database that comes with Visual Basic 2005 allows you to set authorization for specific users based on their being assigned to a role (such as guest, member, manager, etc). You do so in three steps: create the roles, assign permissions to each role, and then assign users to the roles. Any given user may be in more than one role (e.g., administrator and manager). The permissions you assign to each role may determine access to a page, or may change the content of a given page displayed to members of that role.
Create a New Application with Roles
To demonstrate how to create roles and assign users to those roles, you’ll need to create a new application, ASPSecurityRoles. Begin by copying over the web site you used in the previous exercise (FormBasedSecurity), as shown in Figure 12-21.
Figure 12-21.Copy web site
Set Welcome as the Start page and run the program to make sure you can still log in. Open the WAT and click on the Security tab. In the second column (Roles), you’ll see that roles are not enabled. Click on Enable Roles, as shown in Figure 12-22.
Figure 12-22.Enabling roles in WAT
Open Web.config and you’ll see that the WAT has updated it to add roles management:
Depending on how your machine is set up and which database you are using, you may or may not have thedefaultProviderentry in yourWeb.config.
Once roles have been created, use the WAT to create your first Role: Manager (it is helpful to have an initial role and a user in that role so that you can have in your code a test to ensure that only Managers, for example, can create new roles or add users to roles).
What you actually call that role—manager, adminstrator, tsar—is entirely up to you.
Under Add/Remove users, click the Manage link and navigate to one of your users (e.g., jliberty) and click the User Is In Role box to add that user to the role, as shown in Figure 12-23.
Using the LoginView’s smart tag, click on Edit Templates and edit the Logged In Template. Add three hyperlinks to the Logged In Template on the Welcome page, as shown in Figure 12-24. Set the NavigateURL to ChangePW.aspx, CreateAccount. aspx, and ManageRoles.aspx, respectively. Be sure to click on End Template Editing when you are done.
Create the ChangePW.aspx page and drag aChangePasswordcontrol onto the page. Use the smart tag to format theChangePassword control, as shown in Figure 12-25.
Set theContinueDestinationPageURLproperty to Login.aspx, and on Login.aspx make sure theContinueDestinationPageURLof the Login control is set to Welcome.aspx. You may also want to confirm or change the Success Text as well as the other text fields (ChangePasswordTitleText,ChangePasswordFailureText, etc.)
Figure 12-23.Adding users to roles in WAT
Figure 12-24. End Template Editing of Logged In Template
Figure 12-25.ChangePassword control
Create the ManageRoles.aspx page. This new page has a somewhat complex layout since it must display the list of roles and the list of users supported by your site, as well as which users have been assigned which roles. The page is shown in Figure 12-26, and the controls are listed in Table 12-1.
This page is not designed to be pretty, just useful. It is based on a demonstration .aspx page provided by Microsoft.
The code-behind page must implement five event handlers:
Page_Load
AddUsers_OnClick(adding users to roles)
UsersInRoleGrid_RemoveFromRole(removing users from roles)
CreateRole_OnClick(opening panel to create a new role)
btnAddRole_Click(adding new role)
Your class will declare three member variables:
A string array namedrolesArray
A string array namedusersInRole
An instance ofMembershipUserCollectionnamedusers
TheMembershipUserCollection is defined by the Framework to holdMembershipUserobjects (surprise!). AMembershipUserobject, in turn, is defined by the Framework to represent a single user in the membership data store (in this case, the tables created in SqlServerExpress). This class exposes information about the user such as the user’s email address, and methods such as those needed to change or reset the user’s password.
Here’s how the code works. The first step is to override thePage_Loadevent handler, as shown in Example 12-4.
Example 12-4. Page_Load
Protected Sub Page_Load(_ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If User.IsInRole("Manager") = False Then Response.Redirect("NoPrivs.aspx") End If Msg.Text = String.Empty If Not IsPostBack Then rolesArray = Roles.GetAllRoles() RolesListBox.DataSource = rolesArray RolesListBox.DataBind() users = Membership.GetAllUsers() UsersListBox.DataSource = users UsersListBox.DataBind() End If If (RolesListBox.SelectedItem IsNot Nothing) Then usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value) UsersInRoleGrid.DataSource = usersInRole UsersInRoleGrid.DataBind() End If End Sub
First check that the current user is a manager. If he is, a redirect to an error page:
If User.IsInRole("Manager") = False Then Response.Redirect("NoPrivs.aspx") End If
If this is the first time you are displaying the page, get the rolls and bind them to the list box, then get all the users and bind that collection to the Users List Box:
If Not IsPostBack Then rolesArray = Roles.GetAllRoles() RolesListBox.DataSource = rolesArray RolesListBox.DataBind() users = Membership.GetAllUsers() UsersListBox.DataSource = users UsersListBox.DataBind() End If
If there is a selected item in the Roles List Box, get the list of users who are in that role and bind the list to the users in Roll Grid:
If (RolesListBox.SelectedItem IsNot Nothing) Then usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value) UsersInRoleGrid.DataSource = usersInRole UsersInRoleGrid.DataBind() End If
Step 2 is to implement theAddUsers_OnClickevent handler, as shown in Example 12-5.
Example 12-5. AddUsers_OnClick handler
Protected Sub AddUsers_OnClick( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnAddUsersToRole.Click
' A role must be selected If RolesListBox.SelectedItem Is Nothing Then Msg.Text = "Please select a role." Exit Sub End If
' At least one user must be selected If UsersListBox.SelectedItem Is Nothing Then Msg.Text = "Please select one or more users." Exit Sub End If
' Create list of users to be added to the selected role Dim sizeOfArray As Integer = UsersListBox.GetSelectedIndices.Length Dim newUsers(sizeOfArray - 1) As String
'For i As Integer = 0 To newusers.Length - 1 ' newusers(i) = _ ' UsersListBox.Items( _ ' UsersListBox.GetSelectedIndices()(i)).Value 'Next
For i As Integer = 0 To newUsers.Length - 1 ' get the array of selected indices from the (multiselect) list box Dim selectedIndices As Integer() = UsersListBox.GetSelectedIndices() ' get the selectedIndex that corresponds to the counter (i) Dim selectedIndex As Integer = selectedIndices(i) ' get the ListItem in the UserListBox Items collection at that offset Dim myListItem As ListItem = UsersListBox.Items(selectedIndex) ' get the string that is that ListItem's value property Dim newUser As String = myListItem.Value ' add that string to the newUsers collection of string newUsers(i) = newUser Next
' Add users to the selected role Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value) usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value) UsersInRoleGrid.DataSource = usersInRole UsersInRoleGrid.DataBind()
End Sub
First, check to make sure that a role has been selected:
If RolesListBox.SelectedItem Is Nothing Then Msg.Text = "Please select a role." Exit Sub End If
At least one user should be selected:
If UsersListBox.SelectedItem Is Nothing Then Msg.Text = "Please select one or more users." Exit Sub End If
Create an array to hold the users to be added:
Dim sizeOfArray As Integer = UsersListBox.GetSelectedIndices.Length Dim newusers(sizeOfArray - 1) As String
Iterate through the users, retrieving each selected user’s name:
For i As Integer = 0 To newusers.Length - 1 newusers(i) = _ UsersListBox.Items( _ UsersListBox.GetSelectedIndices()(i)).Value Next
This statement is pretty complicated. The best way to understand it is to rewrite it using interim variables, like this:
For i As Integer = 0 To newUsers.Length - 1 ' get the array of selected indices from the (multiselect) list box Dim selectedIndices As Integer() = UsersListBox.GetSelectedIndices() ' get the particular selectedIndex that corresponds to the counter (i) Dim selectedIndex As Integer = selectedIndices(i) ' get the ListItem in the UserListBox Items collection at that offset Dim myListItem As ListItem = UsersListBox.Items(selectedIndex) ' get the string that is that ListItem's value property Dim newUser As String = myListItem.Value ' add that string to the newUsers collection of string newUsers(i) = newUser Next
The advantage of the interim variables is that you can set break points on them and see what their value is, and you can more easily document the code. The disadvantage is minimal, but many programmers (especially those from the “C” culture!) still prefer the terser version.
Next, call the staticAddUsersToRole on theRolesclass, passing in the array of user-names, and the role you want these users added to. Rebind the users who are in that role to theUsersInRoleGrid:
As noted earlier, step 3 is to implementUsersInRoleGrid_RemoveFromRoleas shown in Example 12-6.
Example 12-6. UsersInRoleGrid_RemoveFromRole
Protected Sub UsersInRoleGrid_RemoveFromRole( _ ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls. GridViewCommandEventArgs) _ Handles UsersInRoleGrid.RowCommand
' get the user to remove Dim index As Integer = Convert.ToInt32(e.CommandArgument) Dim username As String = _ CType(UsersInRoleGrid.Rows(index).Cells(0).Controls(0), _ DataBoundLiteralControl).Text
' remove the user Roles.RemoveUserFromRole(username, RolesListBox.SelectedItem.Value) ' Rebind the users in role to Gridview usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value) UsersInRoleGrid.DataSource = usersInRole UsersInRoleGrid.DataBind() End Sub
Step 4 is to add the CreateRole_OnClickevent handler, which makes the CreateRole panel visible, as shown in Example 12-7.
Example 12-7. CreateRole button Click event handler
Protected Sub CreateRole_OnClick( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnCreateRole.Click pnlCreateRole.Visible = True End Sub
The purpose of this is to present the panel, which contains a text box for the user to enter a new role and an Add button, as shown in Figure 12-27.
Figure 12-27.Create new role
Finally, implement thebtnAddRole_Clickevent handler, shown in Example 12-8.
Example 12-8. AddRole button Click event handler
Protected Sub btnAddRole_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnAddRole.Click If txtNewRole.Text.Length > 0 Then Dim newRole As String = txtNewRole.Text
' if the role does not already exist, add it ' rebind the roles list box If Roles.RoleExists(newRole) = False Then Roles.CreateRole(newRole) rolesArray = Roles.GetAllRoles() RolesListBox.DataSource = rolesArray RolesListBox.DataBind() End If End If txtNewRole.Text = String.Empty pnlCreateRole.Visible = False End Sub
Check to make sure there is text in the NewRole text box, and then check to make sure the role does not exist. If it does not, create the new role using the Shared CreateRole method of the Roles class, provided by the Framework.
You do not need an instance ofRolesto callCreateRole becauseCreateRole is Shared.
Get all the roles by calling the Shared methodGetAllRolesand store the roles in the member arrayrolesArray, to which you bind the list box. When the role is added, the text box is cleared and the panel is made invisible.
Run the application and click on Manage Roles to add a couple of roles. Next, click on a role (to highlight it) and highlight one or more users; then click Add User(s) to Role. The results are shown in Figure 12-28.
There are two ways to restrict access to a page based on membership in a Role. The first is to test if the logged-in user is in a particular role, using the User.IsInRole() method:
Dim isManager as boolean = User.IsInRole("Manager")
You might redirect the user to an error page if the user is not in the required role. As an example, let’s add code that blocks nonmanagers from linking to the Manage Roles page. To do so, add a test in thePage_Loadmethod of ManageRoles.aspx.vb:
Protected Sub Page_Load(_ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If User.IsInRole("Manager") = False Then Response.Redirect("NoPrivs.aspx") End If
If the user is not in the role of “Manager,” the user is redirected to the page NoPrivs.aspx. That page can display an error message and then allow the user to take other actions. A very simple example is shown in Figure 12-29.
Figure 12-29. NoPrivs.aspx
The code for the button (btnHome) on the NoPrivs.aspx.vb page, whose text is “Return to Welcome,” is very simple and shown in Example 12-9.
Example 12-9. Return to Welcome button Click event handler
.Protected Sub btnHome_Click(_ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnHome.Click Response.Redirect("Welcome.aspx") End Sub
Restricting Access to a Set of Pages
You can also restrict access to a set of pages by adding an authorization section to a Web.config file. You place this file in a subdirectory to control access to all files in that subdirectory and all of its subdirectories, and you use the location element to control access to specific files:
The first line (deny users='?') prohibits access to anyone who is not logged in. The second line (allow roles='Manager') allows access to anyone in the Manager role, and the final line (deny users='*') disallows everyone, but is overridden by theallow roles.
Now that you have forms-based security working, you know who your user is and can store the user’s preferences and, if appropriate, previous choices (e.g., “You have 3 items in your shopping cart”).
To get started, you’ll want a new project that duplicates the work you accomplished in the previous example. Create a new web site called SitePersonalization and use the CopyWebSite pattern described previously to make a copy of ASPSecurityRoles into the new site (copying over all the files and folders from the old site to the new.) Set Welcome.aspx as the Start page, and run the program to make sure you have a working duplicate.
Recording Personalization Information
The simplest form of personalization is to record information about the user, then make that information available whenever the user logs on. This requires a kind of persistence that goes beyond session state. To create true personalization, you’ll want to store the user’s choices and information in a database that associates the saved information with a particular user, and that persists indefinitely.
ASP.NET 2.0 provides all of the plumbing required. You do not have to design, edit, or manage the database tables; all of that is done for you.
Setting up profile handling
ASP.NET 2.0 has decoupled the Profile API (how you programmatically interact with profile data) from the underlying data provider (how you store the data). This allows you to use the default provider (SqlServerExpress), one of the other providers supplied (SQL server), or even write your own provider (e.g., for an existing Customer Relationship Management system) without changing the way you interact with the profile in the rest of your code.
If you wish to have the SQLExpress database handle the profile information, there are no additional steps; profile tables have already been created for you. To add data to the user’s profile, alert the system about the data you wish to store by making an entry in Web.config. Add a profile section to the<system.web>element, as shown in Example 12-10.
Example 12-10. Adding a profile section to Web.config
Your Web.config file may look somewhat different depending on your machine configuration and the databases you have installed (SQL Server, SQL Express, etc.)
The configuration shown in Example 12-10 causes the Profile API to create storage for four pieces of information: first and last name, phone number, and birth date. The default storage type isString. Notice, however, that you are storing the birth date as aDateTimeobject.
You can gather this personalization information any way you like. For this example, return to Welcome.aspx and click on the smart tag to chooseEditTemplatesand then choose theLoggedIn Template. Set the text toAdd Profile Infoand the NavigateURL property toProfileInfo.aspx(which you will create shortly). Don’t forget to clickEndTemplateEditingwhen you are done.
Create the new page: ProfileInfo.aspx. Add a table, and within the table, labels and checkboxes, as well as a Save button, as shown in Figure 12-30.
The HTML code for the Profile Table is shown in Example 12-11.
All that remains to be done is to add an event handler for the Save button:
Protected Sub save_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles save.Click If Profile.IsAnonymous = False Then Profile.lastName = Me.lastName.Text Profile.firstName = Me.firstName.Text Profile.phoneNumber = Me.phone.Text Profile.birthDate = CType(Me.birthDate.Text, System.DateTime) End If Response.Redirect("Welcome.aspx") End Sub
TheProfile.IsAnonymousproperty is explained in detail below
The Profile object has properties that correspond to the properties you added in Web.config. To test that the Profile object has, in fact, stored this date, you’ll add a panel to the bottom of the Welcome page, as shown in Figure 12-31.
Figure 12-31.Welcome page panel
The panel has a table with three rows, and each row has a label that is initialized to say that the value is unknown (this is not normally needed, but is included here to ensure that the data you see is retrieved from theProfileobject). When the page is loaded, you check to see if you haveProfiledata for this user and, if so, you assign that data to the appropriate controls.
You’ll need to add a bit of code to the Welcome.aspx.vb page, so that when the page loads it will check to see if you have a profile, and if so, it will make the panel visible, as shown in Example 12-13.
Example 12-13. Welcome page Page_Load method
Protected Sub Page_Load(_ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack And Profile.UserName IsNot Nothing Then Me.pnlInfo.Visible = True If Profile.IsAnonymous = False Then Me.lblFullName.Text = Profile.firstName & " " & Profile.lastName Me.lblPhone.Text = Profile.phoneNumber Me.lblBirthDate.Text = Profile.birthDate.ToShortDateString() End If Else Me.pnlInfo.Visible = False End If End Sub
When you start the application, you are asked to log in. Once logged in, a new hyperlink appears: Add Profile Info. This was created by the hyperlink you added to theLoggedInTemplateearlier. Clicking on that link brings you to your new profile page, as shown in Figure 12-32.
Figure 12-32.Profile information page
When you click Save and return to the Welcome page, thePage_Loadevent fires. The Page_Load begins with anIf statement:
If Profile.UserName IsNot Nothing And _ Profile.IsAnonymous = False Then
Both parts of theIfstatement evaluateTrue: theUserNamevalue in the profile is notNothing, and the user is logged in, and thus not anonymous.
Your profile information is displayed, as shown in Figure 12-33.
Stop the application and open the Database Explorer window, and look at the Tables in the aspnetdb database. Open two tables, aspnet_Users (which lists all the users your database knows about) and aspnet_Profile (which lists the profile information for those users). To see these next to each other, click and drag the tab for one of the views, as shown in Figure 12-34.
Figure 12-34. Drag tab
When you let go, a menu will open offering to create a new tab group. Choose New Horizontal Tab Group, as shown in Figure 12-35.
Figure 12-35.Create New Horizontal Tab Group
This done, you can see both the Profile tab and the Users tab in a single window. The Users tab shows you that each user has a uniqueUserID. The Profile tab has a foreign key added into that table (UserID) and lists thePropertyNames andPropertyValues, as shown in Figure 12-36.
Figure 12-36. Profile tables
PropertyNamesmatches up with the entries you created in the<profile>section of Web.config:
Each property is named (e.g.,phoneNumber), given a type (Sfor string), a starting offset (phoneNumberbegins at offset5), and a length (phoneNumber’s value has a length of12). This offset and value are used to find the value within thePropertyValueStringfield.
Notice thatbirthDateis listed as a string, that begins at offset 17 and is 95 characters long; if you look at thepropertyValuesStringcolumn, you’ll find that the birthDate is encoded as XML.
Please check back next week for the continuation of this article.