Chapter 1. The Recipes

1.1. Restricting Access to Views with Password Protection

Problem

You want to prevent access to specific pages of your website unless a user has registered and logged in with a username and password.

Solution

Implement ASP.NET’s AuthorizeAttribute, FormsAuthentication, and Membership creation/validation through the use of an AccountController, AccountModels, and several MVC views.

Discussion

The MVC team at Microsoft have made a lot of improvements to the AccountController. It has been updated to use FormsAuthentication along with the Membership class to create new users, validate existing users, and create cookies to check the logged in state of users.

Unlike MVC 2, in version 3, the new project dialog has been updated to provide several different start up applications: Empty, Internet Application, and Intranet Application. An empty application will set up your folder structure required for MVC. An Internet Application, the default template, will create an MVC application with several features pre-configured, including a basic layout and an AccountController that contains multiple actions to register and log users the application. The third template, Intranet Application, is quite similar to the Internet Application with the exception that instead of using the Membership class, it will use Windows Authentication.

For most websites, the default Internet Application should be used. If you haven’t already done so, create a new MVC 3 Internet Application now. This will ...

Get 20 Recipes for Programming MVC 3 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.