ASP .Net MVC 4 Authorize and AllowAnonymous

João Martins picture João Martins · Sep 27, 2013 · Viewed 16.9k times · Source

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.

Answer

Halleck picture Halleck · Sep 27, 2013

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.