views:

888

answers:

2

Is IAuthorizationFilter coupled with an attribute the preferred way to check if a user is logged in before a controller runs it's course?

Since I'm new to MVC I've been trying to figure out how to handle situations done in WebForms. The one I ran into yesterday is checking to see if the user is able to view a page or not depending on whether logged in or not. When taking a project of mine and "transforming" it into an MVC project, I was a little at odds on how to solve this situation.

With the WebForms version, I used a base page to check if the user was logged in:

if (State.CurrentUser == null)
{
  State.ReturnPage = SiteMethods.GetCurrentUrl();
  Response.Redirect(DEFAULT_LOGIN_REDIRECT);
}

What I did find is this:

[AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext context)
    {
        if (State.CurrentUser ==  null)
        {
            context.Result = 
              new RedirectToRouteResult
              (
                "Login", 
                new RouteValueDictionary
                (
                  new 
                  { 
                    controller = "Login", 
                    action = "Error", 
                    redirect = SiteMethods.GetCurrentUrl()
                  }
                )
              ); 
        }
    }
}

Then I just slap that attribute on any give controller method and life is good. Question is, is this the preferred and/or best way to do this?

+1  A: 

Securing Controller actions using FilterAttributes is a good way to go.

Ropstah
Here is a good blog post on securing your controller actions: http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/
Ropstah
+4  A: 

Don't reinvent the wheel. The MVC framework already includes AuthorizeAttribute, which handles some subtleties not in the code you've pasted here, such as caching. Just use that. But yes, attributes are the way to go.

Craig Stuntz
But what does the Authorize attribute do? What about role membership requirements, or custom Authorization HTTP headers?
Andrew Arnott