views:

376

answers:

3

Hi,

I'm building a small app with ASP.NET MVC and I'm using the ASP.NET membership provider for handling users. Hooked this up to the login page of the basic MVC template.

What is the best practice for checking a valid authentication globaly? I basically want to redirect to the front page or the login page if the user's not authenticated on all my pages.

-anders

+1  A: 

You should just annotate any action you want to authenticate with [Authorize], and optionally with some required roles:

[Authorize()]
public ActionResult Index() {
  ...
  return View();
}

This includes your home page action, if you wish. Unauthorized attempts will be always redirected to the login page.

Palantir
+2  A: 

The way we did it, back in the days of MVC Preview 4 or so, was to create a new "BaseController" class, which every other controller then inherits from. This BaseController class uses the Authorize attribute

[Authorize]
public class BaseController : Controller
{
...
}

The rest of our controllers then inherited from this one

public class HomeController : BaseController
{
...
}

Haven't had to work with MVC for a few months now, so I can't say if this is still applicable, so proceed with caution...

Chris
A: 

this may be slightly over complicated, but another approach could be to put a custom HTTP Module in the pipeline to redirect the request if the user isn't authenticated.

Garry