Posted by: Cirilo Meggiolaro | 04/18/2009

Tip of the day #186 – ASP.NET MVC – Authorization

This tip covers how to put your either controller classes or methods behind an area that requests a user to be authenticated to access.

Basically you have two main ways of providing authentication to your applications: Forms and Windows Authentication. I am not going over those authentication types and how to implement them. The idea of this tip is to show how to define the authorization for your action methods.

How to…

To set up your methods we are going to use the Authorize attribute. Since you add the attribute to either a specific action method or to your whole Controller class the action methods will require a valid authenticated user.

When specifying an Authorize attribute to a method you request that the user must be logged to be able to access the action method:

public ActionResult About()
    return View();

You may define that a user must be logged and this user must be from a specific role:

public ActionResult Manage()
    return View();

It is not a good idea to specify usernames directly on the code but since this option is available be aware that is possible to enforce a user to be logged and to be the one specified on the code. If another username called john tries to access the action method, even if john is logged he will not be able to access it:

public ActionResult About()
    return View();

The same settings are valid for an entire Controller class. If you want to enforce that all action methods under ProductController class will be accessed only for product managers, so you can add the attribute to the class:

public class ProductController : Controller
{ }

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: