Skip to main content

Command Palette

Search for a command to run...

Using the [Authorize] attribute

Published
2 min read
Using the [Authorize] attribute
R

I am a recent graduate at the beginning of my software development career. I enjoy documenting my learnings through my blogs

The [Authorize] attribute is a way to limit access to a particular section of your MVC controller or action to an authenticated user.

I came to find this attribute during a college project where I needed to restrict access to specific pages within my application to users who were logged in. I first attempted to redirect the page to an error page if the user was not logged in, however, this did not work and threw a runtime error, see Custom error pages for HTTP status codes in ASP.NET MVC for more information on creating custom error pages.

I instead used the [Authorize] attribute on certain actions within my relevant controller, see Simple Authorization for more information on the [Authorize] attribute. For example, I used the [Authorize] to redirect a link to the login page if a user was not logged in. The redirect is simply a side-effect of the user not being signed in when trying to access a route (Controller action) that is decorated with an [Authorize] attribute. In doing this I did not have to redirect to an error page when a User was not logged in and I used the [Authorize] attribute in its most simple form.

[Authorize]
public ActionResult AddToFavourites(int id)
{
     ...
}

The [Authorize] attribute can be used on the controller itself or each individual action. Using the [Authorize] attribute on the controller causes the MVC app to check if a user is logged in before carrying out any actions within the controller.

[Authorize]
public class RecipesController : Controller 
{
     ...
}

I used the [Authorize] attribute very simply, on specific action methods, however upon my further learning into the [Authorize] I found that when using the attribute on the controller, you can use the [AllowAnonymous]. This [AllowAnonymous] attribute can be used to display certain pages to a user even if they are not logged in, such as the home page or the login page. This seems a better and cleaner way to use these attributes if most pages require authentication to view, however, if only one or two pages need authentication, using the [Authorize] attribute over each action method is simpler. For example, in my project I only needed to limit and edit a page and a favourites page, so using the [Authorize] attribute on the whole controller would not have made sense

Note: the [Authorize] attribute can be made more specific, for example, will only authorize named users [Authorize(Users = “Mary, John”)] or users with certain roles [Authorize(Roles = “Admin”)].