9.3. Restricting Access to Application Pages by Role
Problem
You want to assign or make use of predefined roles for the users of your application, and you want to control access to pages as a function of these roles.
Solution
The solution involves the following four steps:
Implement the solution described in Recipe 9.2, adding the required roles to web.config for each of the pages.
In the code-behind class for the ASP.NET login page, add the user’s role information to the authentication cookie when the user logs in.
Add code to the
Application_AuthenticateRequest
method in the global.asax file to recover the user role information and build a user principal object.Set the user principal object to the
Context.User
property to provide ASP.NET the data it needs to perform page-by-page authentication.
The code we’ve written to illustrate this solution appears in Examples 9-6, 9-7, 9-8, 9-9 through 9-10. The <authentication>
and <authorization>
elements of web.config are shown in Example 9-6. The login page code-behind where the authentication cookie is created is shown in Examples 9-7 (VB) and 9-8 (C#). (See Recipe 9.1 for the .aspx file for a typical login page.) The Application_AuthenticateRequest
method in the code-behind for global.asax is shown in Examples 9-9 (VB) and 9-10 (C#).
Discussion
The approach we favor for this recipe builds on Recipe 9.2 but takes a tack of its own based on the addition and use of user roles. The <authentication>
and <authorization>
elements of the web.config ...
Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.