Title- asp.net-mvc5 Auto logout How to make form auto logout after sometime in asp.net-mvc5 and redirect automatically to login page
How to make auto logout page in mvc after a some time
4.9k Views Asked by Vijay Dwivedi At
3
There are 3 best solutions below
0
On
You should add Statup.cs file.
1. Add Statup Class your project from new item lists.
2. Add following line in ConfigureService.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.EnableEndpointRouting =
false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddAuthorization();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// we do this because we trust the network
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.Cookie.Name = "WriteSomeThings";
x.Cookie.SecurePolicy = CookieSecurePolicy.Always;
x.Cookie.SameSite = SameSiteMode.Strict;
x.Cookie.HttpOnly = true;
x.Cookie.IsEssential = true;
x.SlidingExpiration = true;
x.ExpireTimeSpan = TimeSpan.FromHours(8);//For Auto Logout
x.LoginPath = "/User/LogOn";
x.LogoutPath = "/User/LogOff";
x.AccessDeniedPath = "/Home/AccessDenied";
});
}
x.ExpireTimeSpan = TimeSpan.FromHours(8) => This line allow us to logout automatically after 8 hours.
You need to create a session variable on the
Loginmethod. The session will be created bySession["Userid"]=Userid;. Then you need to create custom attribute to check session timeout. Steps you need to follow are:Copy and paste below code in that file.
public class SessionTimeOutAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) {
}
add [SessionTimeOut] attribute on each controller.
[SessionTimeOut]
public class ControllerName : Controller {