# Using the [Authorize] attribute

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](https://rachael.hashnode.dev/custom-error-pages-for-http-status-codes-in-aspnet-mvc) [ASP.NET](http://ASP.NET) [MVC](https://rachael.hashnode.dev/custom-error-pages-for-http-status-codes-in-aspnet-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](https://jakeydocs.readthedocs.io/en/latest/security/authorization/simple.html#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.

```csharp
[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.

```csharp
[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”)]`.
