I just learning ASP.NET MVC and newbie in it so I can't find the solution for some problem. Maybe somebody faced this problem and can give me advice? Thanks for all!
In my project, I use ASP.NET Identity for authorization. The only problem I faced is how to redirect the user to login page after session expires. If action from controller called not from AJAX it works well, but if action called from AJAX function it crashes. I search for the solution, but everything I found not working for me. Now my code looks like:
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>
Function from JS which calls 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 controller I 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);
}
}
}
