9.5. Using Membership and Roles


You want to secure your web site by writing only a minimum amount of code.


Use ASP.NET 2.0’s Membership and Role providers. The solution involves the following steps:

Modify web.config as follows:

  1. Add the <authentication>, <authorization>, and <location> elements, as described in Recipe 9.3.

  2. Add a <membership> element with a <provider> element defining the provider used to authenticate users.

  3. Add a <roleManager> element with a <provider> element defining the provider used to manage the roles for users of your application.

In the .aspx file for the login page:

  1. Add a Login control.

  2. Customize the Login control as required by your application.

In the .aspx file for pages in your application, optionally add an <asp:LoginName> control to display the logged in user’s name and an <asp:LoginStatus> control to provide the ability to log out.

The code we’ve created to illustrate this solution is shown in Examples 9-15, 9-16 through 9-17. Example 9-15 shows the modifications we make to web.config to use the Membership and Role providers. Example 9-16 shows the .aspx file for the login page, and Example 9-17 shows the .aspx file for a page that displays the user’s name and provides the ability to log out of the application.


ASP.NET 1.x simplified the coding required to control access to pages in your application. The infrastructure to handle authentication and authorization for pages in your application requires no code in the individual pages; however, ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.