Custom Authorize Attribute & Forms authentication

2019-09-11 04:01发布

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条回答
▲ chillily
2楼-- · 2019-09-11 04:43

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

        }
    }
查看更多
我只想做你的唯一
3楼-- · 2019-09-11 04:59

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.

查看更多
登录 后发表回答