[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class AuthenticateAttribute : ActionFilterAttribute
{
private const string RequestedWithHeader = "X-Requested-With";
private const string XmlHttpRequest = "XMLHttpRequest";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session.GetString("SessionData") == null)
{
if (filterContext.HttpContext.Request.Headers[RequestedWithHeader] == XmlHttpRequest)
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 401;
}
else
{
bool NoFilter = true;
foreach (var filterDescriptors in filterContext.ActionDescriptor.FilterDescriptors)
{
if (filterDescriptors.Filter.GetType() == typeof(IAllowAnonymous))
{
NoFilter = false;
return;
}
}
if (NoFilter)
{
var url = filterContext.HttpContext.Request.GetDisplayUrl();
filterContext.Result = new RedirectToPageResult("/Account/Login", new { area = "Identity", returnUrl = url });
}
}
}
base.OnActionExecuting(filterContext);
}
}