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?