How to force the user to login to see any content using ASP.NET MVC 4

Leron_says_get_back_Monica picture Leron_says_get_back_Monica · Nov 22, 2013 · Viewed 11.7k times · Source

I am working on a 'ASP.NET MVC 4' application and use 'SimpleMembershipProvider'. The application will be used in intranet and there will be no content available for not authorized users so I want to force login before letting the user to the actual site content.

I think this should be rather trivial task but it's the first time I have to implement such logic and I also want to do it MVC 4/SimpleMemebrship style so I seek advice.

The way I think it should be implemented is first to add this in the web.config:

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

after all I won't have action that will allow anonymous so I think it's better to put this here.

And changing my default Route to:

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );

Which as I see it, will be the only action that will allow anonymous. However I'm a little bit concerned about changing the default route to Login I'm not sure if this won't lead to some unexpected drawbacks.

I also have the idea to keep the default structure created by the MVC 4 Internet Template and just leaving the Index action of the Home controller taking responsibility but I don't like this scenario because the logic is clear - the user must be logged in in order to gain any kind of access and even Home/Index is some access in my mind.

So what is the way to implement such kind of behavior? What are the basic steps, changes that I should make in order to implement this right?

Answer

Uroš Goljat picture Uroš Goljat · Nov 24, 2013

You can achieve this by registering Authorize attribute as global filter. Bellow is an example of how your RegisterGlobalFilters method should look like:

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

with this in place, you'll have to allow anonymous users to access the login page. To do that you annotate your Login action method with AllowAnonymous attribute.

[AllowAnonymous]
[HttpGet]
public ActionResult Login()
{
 ...
}

Do the same for Login action method that receives POST request.