Leron
Leron

Reputation: 9866

How to deny all authenticated user access with SimpleMembershipProvider in ASP.NET MVC 4

I am working on ASP.NET MVC 4 application that is using SimpleMembershipProvider. It turns out that all the content will require authentication and colleague of mine told me that adding this:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" />
</authentication>

If fact I already had this - <forms loginUrl="~/Account/Login" timeout="2880" /> so I guess the key is protection="All" but the problem is that it's not working. At least not the way that I expect it to.

When I start my application I'm still routed to /home/index (haven't changed the default route) but if I add [Authorize] :

[Authorize]
public class HomeController : Controller

then I'm getting redirected to the login page.

I wasn't able to find explanation about the different attributes used in <forms../> and the different values that they can take, but it seems logical that the one that should make all controllers behave like they have [Authorize] attribute is protection="All" so am I using it in a wrong way or this attribute can not be used with SingleMembershipProvider or something else?

Upvotes: 0

Views: 856

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

but it seems logical that the one that should make all controllers behave like they have [Authorize] attribute is protection="All"

No, that's not at all. Forms Authentication existed in ASP.NET much before ASP.NET MVC was even in the heads of the Microsoft's teams designers.

protection="all" simply specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

Now if you want to protect all controllers in your application, you could decorate them with the [Authorize] attribute or define it as a global action filter:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new AuthorizeAttribute());
}

Now of course if all controller actions in your application require an authenticated user in order to access them, there's no way for an anonymous user to actually authenticate. You probably want to exclude the AccountController that will perform the actual authentication. This could be achieved by decorating it with the [AllowAnonymous] attribute.

Upvotes: 2

Related Questions