Using the Authorize Attribute to Require Login

The first, simplest step in securing an application is requiring that a user be logged in to access specific URLs within the application. You can do that using the Authorize action filter on either a controller or on specific actions within a controller. The AuthorizeAttribute is the default Authorization filter included with ASP.NET MVC. Use it to restrict access to an action method. Applying this attribute to a controller is shorthand for applying it to every action method within the controller.

Authentication and Authorization

Sometimes people get confused with respect to the difference between user authentication and user authorization. It's easy to get these words confused—but in summary, authentication is verifying that users are who they say they are, using some form of login mechanism (username/password, OpenID, and so on—something that says “this is who I am”). Authorization is verifying that they can do what they want to do with respect to your site. This is usually achieved using some type of role-based system.

Without any parameters, the Authorize attribute just requires that the user is logged in to the site in any capacity—in other words, it just forbids anonymous access. You look at that first, and then look at restricting access to specific roles.

Securing Controller Actions

Let's assume that you've naively started on your music store application with a very simple shopping scenario: a StoreController with two actions: ...

Get Professional ASP.NET 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.