Adding Roles to ASP.NET Accounts - Restricting Access to Pages Based on Roles
(Page 2 of 4 )
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:
<authorization>
<deny users='?' />
<allow roles='Manager' />
<deny users='*' />
</authorization>
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.
Next: Create Personalized Web Sites >>
More Visual Basic.NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter 12 of the book Programming Visual Basic 2005, written by Jesse Liberty (O'Reilly, 2005; ISBN: 0596009496). Check it out today at your favorite bookstore. Buy this book now.
|
|