0
votes

I Have a custom Authorize Attribute, that simply looks like this so far: (I'll add more logic later. I just want to see this work first).

public class CustomAuthorizeAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        base.OnAuthorization(filterContext);
    }

}

Then I place my attribute onto a controller:

[CustomAuthorize(Order = 0)]
public class MyController : Controller

Now,

This all works well & dandy, until my forms authentication runs out.

I.E

<forms loginUrl="~/myController/myMethod" timeout="30" /> // this timout expires.

After this timeout, my custom authorize attribute no longer gets hit, instead, it seems that the forms auth module takes over.

After the timeout, the forms auth module just returns the view rendered by the action specified in the webconfig code above.

I'd like to intercept the onAuthorize action when the timeout has expired, so I can interrogate the HttpContext for certain things, and conditionally redirect the user.

Has anyone done something similar?

2
How do you know your custom authorize attribute is no longer hit when the timeout occurs? In your example the custom authorize attribute does nothing but pass control to the AuthorizeAttribute, so that is the behavior you will see. It should always hit CustomAuthorizeAttribute regardless of the authentication state. You can grab events around authentication in the Global.asax, such as FormsAuthentication_OnAuthenticate. - Kevin Junghans

2 Answers

1
votes

Actually that the default behavior


If you what to handle situations when the user is not authenticated the override:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
      //your logic
      //...
      //...

      base.HandleUnauthorizedRequest(filterContext);
}

Or you can inherit from the ActionFilterAttribute and check the if the User is authenticated in your custom action filter. This will allow you to bypass the Forms authentication issues that you are experiencing.

Some thing like this:

public class CustomAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    //code that handles unauthorized ajax request
                }
                else
                {
                    //code that handles http request
                }
            }

            //you custom authorization logic

        }
    }
0
votes

You could insert code into the HttpApplication.AcquireRequestState to watch for whether the authentication is valid anymore and redirect at that point. Take a look at MSDN for more information on the event.