Restricting Access to an Action Method
Many Web applications require users to log in before the users are granted access to restricted content. In some applications, even users who are logged in might have restrictions on what content they can view or what fields they can edit.
To restrict access to an ASP.NET MVC view, you restrict access to the action method that renders the view. To accomplish this, the MVC framework provides the AuthorizeAttribute class.
Using the Authorize Attribute
When you mark an action method with the Authorize attribute, access to that action method is restricted to users who are both authenticated and authorized. If you mark a controller with the attribute, all action methods in the controller are restricted.
The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users. This gives you a high degree of control over who is authorized to view any page on the site.
If an unauthorized user tries to access a method that is marked with the Authorize attribute, the MVC framework returns a 401 HTTP status code. If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.
Example Controller
The following example shows three ways to use the Authorize attribute. The HomeController class has three action methods that are marked with the Authorize attribute, and two that are not marked. On the AuthenticatedUsers method, the attribute limits access to users who are logged in. On the AdministratorsOnly method, the attribute limits access to users who have been assigned to either the Admin role or the Super User role. On the SpecificUserOnly method, the attribute limits access to the users whose names are Betty or Johnny. The Index and About methods can be accessed by anyone, even anonymous users.
<HandleError()> _
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
ViewData("Message") = "Welcome to ASP.NET MVC!"
Return View()
End Function
Function About() As ActionResult
Return View()
End Function
<Authorize()> _
Function AuthenticatedUsers()
Return View()
End Function
<Authorize(Roles:="Admin, Super User")> _
Function AdministratorsOnly()
Return View()
End Function
<Authorize(Users:="Betty, Johnny")> _
Function SpecificUserOnly()
Return View()
End Function
End Class
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
[Authorize]
public ActionResult AuthenticatedUsers()
{
return View();
}
[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
[Authorize(Users = "Betty, Johnny")]
public ActionResult SpecificUserOnly()
{
return View();
}
}