ASP.Net MVC: Log out User in case of session timeout with ASP.NET MVC5 with OWIN Authentication.
When you are using OWIN authentication in ASP.Net MVC 5 and also session to store your value. Then you need your user to be redirected to the Login page in case of session expire. I searched so many blogs and found so many ways to do that, but what fits with my requirement is this what i want to share it with you all.
For this there are several steps you need to do as below:
Step 1:
You need to create a new ActionFilterAttribute. This you need to create inside the Filterconfig class in the App_Start folder and then you need to add you filter in the RegisterGlobalFilters method. You calss to be look like below:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CheckSessionOutAttribute());
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CheckSessionOutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim();
string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();
if (!actionName.StartsWith("login") && !actionName.StartsWith("sessionlogoff"))
{
var session = HttpContext.Current.Session["SelectedSiteName"];
HttpContext ctx = HttpContext.Current;
//Redirects user to login screen if session has timed out
if (session == null)
{
base.OnActionExecuting(filterContext);
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Account",
action = "SessionLogOff"
}));
}
}
}
}
}
Step 2:
You need to create the above actionresult method which you have defined in your ActionFilter.
In that methind you need to singout the user from the OWIN. and redirect the user to a controller action which need login. Then the user will automatically be redirected to the Login view. If you are using this with ajax call through jquery then you need to do the Step 3.
public ActionResult SessionLogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
Step 3:
in the ajax call you need to track the success code where you will get the 401 code and based on that you need to redirect the user to the authorized controller action or login action.
$.ajax({
type: "GET",
url: '@Url.Action("Step1", "Home")',
statusCode: {
401: function (data) {
// the user is not authenticated => redirect him to the login page
window.location.href = '@Url.Action("Login", "Account", new { Area = "" })';
}
},
success: function (resultdata) {
//Do your work with resultdata
},
error: function (errorThrown) {
}
});
I hope this will help you people Lot. Let me know you feedback. :)
For this there are several steps you need to do as below:
Step 1:
You need to create a new ActionFilterAttribute. This you need to create inside the Filterconfig class in the App_Start folder and then you need to add you filter in the RegisterGlobalFilters method. You calss to be look like below:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CheckSessionOutAttribute());
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CheckSessionOutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim();
string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();
if (!actionName.StartsWith("login") && !actionName.StartsWith("sessionlogoff"))
{
var session = HttpContext.Current.Session["SelectedSiteName"];
HttpContext ctx = HttpContext.Current;
//Redirects user to login screen if session has timed out
if (session == null)
{
base.OnActionExecuting(filterContext);
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Account",
action = "SessionLogOff"
}));
}
}
}
}
}
Step 2:
You need to create the above actionresult method which you have defined in your ActionFilter.
In that methind you need to singout the user from the OWIN. and redirect the user to a controller action which need login. Then the user will automatically be redirected to the Login view. If you are using this with ajax call through jquery then you need to do the Step 3.
public ActionResult SessionLogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
Step 3:
in the ajax call you need to track the success code where you will get the 401 code and based on that you need to redirect the user to the authorized controller action or login action.
$.ajax({
type: "GET",
url: '@Url.Action("Step1", "Home")',
statusCode: {
401: function (data) {
// the user is not authenticated => redirect him to the login page
window.location.href = '@Url.Action("Login", "Account", new { Area = "" })';
}
},
success: function (resultdata) {
//Do your work with resultdata
},
error: function (errorThrown) {
}
});
I hope this will help you people Lot. Let me know you feedback. :)
Hello ,
ReplyDeletefor my same issue i used your code but my application in loop to many redirect . How i solved this problem
Sorry to reply late. is your problem resolved? If not then can i get the detail of your code sample how you have implemented then i may resolve?
DeleteCode is
ReplyDeletepublic class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (filterContext.HttpContext.Session["AdminId"] == null)
{
var auth = filterContext.HttpContext.GetOwinContext().Authentication;
auth.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
filterContext.HttpContext.Response.Redirect("~/Home/Login?sessionExpired=Your session has expired, please login again.");
}
base.OnActionExecuting(filterContext);
}
}