Simple authorization

If you have worked with ASP.NET MVC before, you may already be familiar with authorization. The [Authorize] and [AllowAnonymous] attributes are the inbuilt authorization components in the framework. At the simplest level, applying the [Authorize] attribute over a Controller or action restricts the access to the Controller or action to authenticated users only. If you apply the [Authorize] attribute to a Controller, it applies to all the actions:

[Authorize]
public class AccountController : Controller
{
public ActionResult Login()
{
}

public ActionResult Logout()
{
}
}

In the preceding code, only authenticated users have access to the Login action as well. This doesn't make sense as I want to log in when I am not logged in, and not when I am already logged in. So if you want it to be applied to only a few actions, then apply the attribute to those actions alone. The other way to prevent this situation is to use the [AllowAnnonymous] attribute on the Login action, and that makes it accessible to non-authenticated users as well.

Treat [AllowAnonymous] like a 0,  and [Authorize] as 1. So if you apply [Authorize] on the Controller and [AllowAnonymous] on an action, that action will be accessible anonymously (1 x 0 = 0), while other actions will require authentication. On the contrary, if you apply [AllowAnonymous] on the controller and [Authorize] on an action, all the actions will be accessible anonymously. The reason for this is that anything multiplied by 0 is 0, so if you apply [AllowAnonymous] on the Controller, all other action level attributes are bypassed.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset