9.3. Restricting Access to Application Pages by Role
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.
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_AuthenticateRequestmethod 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.Userproperty 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
<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#).
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
<authorization> elements of the web.config ...