2 out of 4 rated this helpful - Rate this topic

AuthorizeAttribute Class

Represents an attribute that is used to restrict access by callers to an action method.

System.Object
  System.Attribute
    System.Web.Mvc.FilterAttribute
      System.Web.Mvc.AuthorizeAttribute

Namespace:  System.Web.Mvc
Assembly:  System.Web.Mvc (in System.Web.Mvc.dll)
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, Inherited = true, 
	AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, 
	IAuthorizationFilter

The AuthorizeAttribute type exposes the following members.

  Name Description
Public method AuthorizeAttribute Initializes a new instance of the AuthorizeAttribute class.
Top
  Name Description
Public property Order Gets or sets the order in which the action filters are executed. (Inherited from FilterAttribute.)
Public property Roles Gets or sets the user roles.
Public property TypeId Gets the unique identifier for this attribute. (Overrides Attribute.TypeId.)
Public property Users Gets or sets the authorized users.
Top
  Name Description
Protected method AuthorizeCore Determines whether access to the core framework is authorized.
Public method Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Returns the hash code for this instance. (Inherited from Attribute.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method HandleUnauthorizedRequest Processes HTTP requests that fail authorization.
Public method IsDefaultAttribute When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method OnAuthorization Called when a process requests authorization.
Protected method OnCacheAuthorization Called when the caching module requests authorization.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Explicit interface implemetation Private method _Attribute.GetIDsOfNames Maps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.GetTypeInfo Retrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.Invoke Provides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

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.

For more information about using attributes, see Extending Metadata Using Attributes.

This topic contains the following sections:

Using AuthorizeAttribute

When you mark an action method with AuthorizeAttribute, 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.

Deriving from AuthorizeAttribute

If you derive from the AuthorizeAttribute class, the derived type must be thread safe. Therefore, do not store state in an instance of the type itself (for example, in an instance field) unless that state is meant to apply to all requests. Instead, store state per request in the Items property, which is accessible through the context objects passed to AuthorizeAttribute.

The following example shows several ways to use AuthorizeAttribute. 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 : 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();
     }
 }


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Custom not-authorised behaviour?
" 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. " $0$0 $0 $0What if the site is configured for integrated authentication? Can a page be configured as the "unauthorised" page?$0
Using AD
To use a group in Active Directory you would list the name of the group(s) in the Roles property.

[Authorize(Roles = @"domainname\Admin")]
public ActionResult AdministratorsOnly()
{
  return View();
}
Using AD Groups
We need an example using AD Groups.
return RedirectToSignin(...);

I needed an alternative to [Authorize] which does the same thing, but affords me the opportunity to do the authentication checking within the action method.

More here: http://www.lukepuplett.com/2010/08/aspnet-mvc-2-redirecttosignin.html

        protected ActionResult RedirectToSignin(string returnAction, string returnController, 
object returnRouteValues, RequestContext requestContext)
{
UrlHelper u = new UrlHelper(requestContext);

string returnUrl = UrlHelper.GenerateUrl(
null, returnAction, returnController, new RouteValueDictionary(returnRouteValues),
u.RouteCollection, requestContext, true);

string baseAddress = String.Format("{0}://{1}",
HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority);

return Redirect(String.Format("{0}/Customer/Signin?returnUrl={1}",
baseAddress, returnUrl));
}