Consider the following code:
[Authenticate(Order = 1)]
public ActionResult SomeActionThatRequiresAuthentication()
{
var model = new SomeViewModel();
// Do something with an authenticated session/user...
return View(model);
}
Does the Authenticate
attribute happen before or after the code inside the SomeActionThatRequiresAutehntication
method is executed?
I am asking this because I have a Attribute that does something like this:
public class Authenticate : CustomAuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!UserService.IsAuthenticated && !HttpContext.Current.Response.IsRequestBeingRedirected)
HttpContext.Current.Response.Redirect(ViewUtil.Actions.User.LogOnUrl());
}
}
As you can see the attribute will redirect a user if the user is not authenticated. However it appears that the redirect only happens after the action executes. This is causing problems because I made the assumption the user is authenticated when executing the action. First I need to understand if the attributes are supposed to happen before or after the action is executed, or am I thinking of the workflow completely wrong?
Thanks, Paul
After researching this some more it is clear that the filterContext.Result
has to be set for this to work. After making a small change in my Authorize attribute, it is now working:
public class Authenticate : CustomAuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!UserService.IsAuthenticated && !HttpContext.Current.Response.IsRequestBeingRedirected)
filterContext.Result = new RedirectResult(ViewUtil.Actions.User.LogOnUrl());
}
}