Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .Net MVC 4 Authorize and AllowAnonymous

I am completely new with this framework and I am still learning the basics of it and C#. Meanwhile, I came across with the attributes Authorize and AllowAnonymous while reading a book and I can't understand how a controller "knows" if the user trying to access those methods/actions is authenticated or not. Where is that information stored? Do I need to to have a special treatment while performing the login method?

Thanks for any help.

like image 239
João Martins Avatar asked Sep 27 '13 16:09

João Martins


People also ask

What is the use of AllowAnonymous in MVC 4?

AllowAnonymous lets users who have not been authenticated access the action or controller.

What is AllowAnonymous in MVC?

The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. [AllowAnonymous] public ActionResult NonSecured() { return View();

What is AllowAnonymous?

One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.

How do you use AllowAnonymous?

[AllowAnonymous] bypasses all authorization statements. If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) are ignored.


1 Answers

Assuming that you have some sort of authentication setup in your application (forms authentication, windows authentication or OAuth) a logged in user has a token stored on their browser in the form of a cookie. When a user navigates your application, their token is passed along with them. When the Authorize attribute is applied to one of your controller methods, your application examines their token and if they are an authenticated user with the correct permissions, it allows them in, if not it will redirect them to an action you have specified. The default redirect is to the registration/login page. AllowAnonymous lets users who have not been authenticated access the action or controller.

In short, it knows based on the token it receives from the client.

As for the second question, if you selected "internet application" when you made your MVC 4 project, forms authentication is built in for you and you don't need to do anything but use the generated login action. If you wish to use a database other than the one the generated code makes, you will need to implement MembershipProvider and MembershipUser.

like image 196
Halleck Avatar answered Sep 28 '22 03:09

Halleck