I'm currently learning ASP.NET MVC and I'm a newbie in it, so I'm struggling to find a solution for a specific problem. If anyone has encountered this issue before, I would appreciate any advice. Thank you!
In my project, I am using ASP.NET Identity for authorization. The main issue I'm facing is how to redirect the user to the login page after the session expires. Everything works fine if the action is initiated from a controller and not through AJAX. However, when the action is triggered through an AJAX function, it crashes. I've been searching for a solution but haven't found anything that works for me yet. Currently, my code looks like this:
Startup.cs
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
LogoutPath = new PathString("/Home/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(1),
});
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="1" />
</authentication>
</system.web>
The JS function that calls the action:
function click(d) {
//Some logic
$.ajax({
url: '@Url.Action("GetDataForNode", "Home")',
type: 'POST',
dataType: 'json',
cahe: false,
data: { uid: d.id, index: index, nodesUid: nodesUid, request },
success: function (results) {
//Some logic
},
error: function (xhr) {
if (xhr.status === 401) {
window.location.href = xhr.Data.LogOnUrl;
return;
}
}
})
}
And in the controller, I have created:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new JsonResult
{
Data = new
{
Error = "NotAuthorized",
LogOnUrl = FormsAuthentication.LoginUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Upon execution, I encounter this https://i.stack.imgur.com/Rg52t.png