We are using Ajax call across the application- trying to find out a global solution to redirect to login page if session is already expired while trying to execute any Ajax request. I have coded following solution taking help from this post - Handling session timeout in ajax calls
NOT SURE WHY IN MY CARE EVENT "HandleUnauthorizedRequest" DOES NOT GET FIRED.
Custom Attribute:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CheckSessionExpireAttribute :AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var url = new UrlHelper(filterContext.RequestContext);
var loginUrl = url.Content("/Default.aspx");
filterContext.HttpContext.Session.RemoveAll();
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.HttpContext.Response.Redirect(loginUrl, false);
filterContext.Result = new EmptyResult();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Using Above custom attribute as follow in controller action:
[NoCache]
[CheckSessionExpire]
public ActionResult GetSomething()
{
}
AJAX Call(JS part):
function GetSomething()
{
$.ajax({
cache: false,
type: "GET",
async: true,
url: "/Customer/GetSomething",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
}
Web Config Authentication settings:
<authentication mode="Forms">
<forms loginUrl="default.aspx" protection="All" timeout="3000" slidingExpiration="true" />
</authentication>
I am try to check it by deleting browser cooking before making ajax call but event "CheckSessionExpireAttribute " does not get fired- any idea please.
Thanks,
@Paul
.ASPXAUTH
cookie before sending the request? – IlldisposedSession
is used to store variable between request for a specific user in either the web server's memory or some other persistent storage mechanism. The end user is typically given a cookie with aSession Id
. An authentication cookie (or token) is typically an encrypted cookie that stores your logout expiration time and your user id or user name. The web server uses this to ensure you are an authenticated user and are authorized for the request you made. You can have only session, only authorization, neither or both. They are completely independent of each other. – Ratliffstartup.cs
file (#27028248). Lastly, here is an SO answer discussion this topic - #17813494 – Ratlifferror: function (xhr, ajaxOptions, thrownError) { if(xhr.status === 403){ location.href = '/Default.aspx' } }
remove thefilterContext.HttpContext.Response.Redirect(loginUrl, false);
which wont have any effect – Idioglossia