ASP.NET Core not redirecting to logIn page after session times out

10,099

The Lockout.DefautLockoutTimeSpan is meant to be how long the user should be locked out before (s)he can re-authenticate again, if you have Lockout enabled in ASP.NET Identity. It's not the time span for how long before the session times out.

To enable session middleware, you can use Microsoft.AspNetCore.Session package.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
       ...
       services.AddSession(options =>
       {
           options.IdleTimeout = TimeSpan.FromSeconds(60);
           options.Cookie.HttpOnly = true;
       });
       ...
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
        ...
    }
}

But I thought IdleTimeout is used by the server to determine how long a session can be idle before its contents are abandoned. I thought session is used to pass data from page to page. So if the IdleTimeout happens, all the data stored in session would be gone.

But by reading from your question, I thought you just want the site to prompt the user when (s)he is about to be logged out due to inactivity. If the app can logout the user automatically based on the time span, it would be not user friendly, because the user might be in the middle of something.

If you want to perform an action after a period of time, i.e., no activity on the page after 2 hours, there are jQuery plugins to help you detect session timeout. Unfortunately I forgot the name of the one I used before. I am sure you can easily google one, like https://plugins.jquery.com/sessionTimeout/

Share:
10,099
nam
Author by

nam

Updated on June 15, 2022

Comments

  • nam
    nam almost 2 years

    I've following configuration I've LockOut.DefaultLockoutTimeSpan set to 2 hours and ApplicationCookie.ExpireTimeSpan set to one day. But if the app is idle for 2 hours it does not redirect the user to login page. In the View below, I'm using Ajax where a click event of a tab in a tabstrip gets an id of the tab and passes it to a calling action method. But I noticed that if I leave the app idle for 2 hours and click on the tab it passes the id value as null and hence, as expected, the action method fails and the alert message in the error block of Ajax method is displayed. Question: How can I make the app to redirect to login page when login session expires? Obviously, I'm missing something in the code below. I'm using ASP.NET Identity-3 for authentication.

    UPDATE:

    What is happening is that I've three important session variables that are storing some values that are used across the pages. And those values are getting lost after every 15-20 minutes or so. And hence application is throwing error message in the alert(...) dialog of error blocks of Ajax code. So I thought it has something to do with authentication cookie expiring earlier. But it seems the issue is more related to session expiring earlier than I need it to.

    StartUp.cs

    ...
    public void ConfigureServices(IServiceCollection services)
    {
       ...
    
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
        services.AddMvc();
        services.AddDistributedMemoryCache();
        services.AddSession();
    
        services.Configure<IdentityOptions>(options => {
            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(120); //The amount of time in minutes a user is locked out when a lockout occurs
    
            // Cookie settings
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1); //Controls how much time the authentication ticket stored in the cookie will remain valid from the point it is created. Defaults to 14 days.
            options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn"; //When a user is unauthorized, they will be redirected to this path to login. Defaults to /Account/Login.
            options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
        });
    
        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }
    ...
    

    MyView:

    <html>
    ...
    <div>Tabstrib here with tab1, tab2</div>
    ...
    @section scripts
    {
        @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
        <script>
            $(document).ready(function () {
                ...
    
            $('#myTabstripID li').click(function () {
                var li_id = $(this).attr("id");
                $.ajax({
                    url: '@Url.Action("ActionName", "ContrlName")',
                    data: { calledFrom: li_id },
                    contentType: 'application/json',
                    dataType: 'html',
                    type: 'GET',
                    cache: false,
                    success: function (data) {
                        if (li_id == 'Tab1')
                            $('#menuAP').html(data);
                        else if (li_id == 'Tab2')
                            $('#menuUP').html(data);
                    },
                    error: function (jqXHR, textStatus) {
                        alert('Error occurred');
                    }
                });
            });
        ...
    }
    
    • Afshar Mohebi
      Afshar Mohebi over 6 years
      When an Ajax call hits a web site while that website requires re-authentication, shouldn't it return a 401 (Authorization required) response instead of redirecting to login page? I think it is the nature of Web API.
    • nam
      nam over 6 years
      @Afshar I'm not using Web API - It's a web application. But I see your point. The issue may seem to be related to session variables expiring - I've added an UPDATE section to the post for that. Would you have an idea on how to resolve the session variable related issue?
  • nam
    nam over 6 years
    Good point. So how do I set the time to, say, 2 hours before app logs the user out?
  • David Liang
    David Liang over 6 years
    I used the jQuery timeout plugin, where you can set the time span so that after the time span expires, an action will be performed. You can set that action to be logging the user out? Again I had used a library to do the exact same thing before but I just forgot the name.
  • nam
    nam over 6 years
    But I though ASP.NET Core has some configuration settings for setting that time period, correct?
  • David Liang
    David Liang over 6 years
    Please see my update. There is a way to enable session, but I thought session is used to carry data from page to page. So if the session timeout happens, all the data stored in the session will be disappeared. Correct me if I am wrong but I thought you meant to log the user out if there is no activity on the page.
  • nam
    nam over 6 years
    Now that you've introduced some plugins for detecting session timeout I would be interested in those as well. But you actually helped me clearing my own confusion. Hence, I've added an UPDATE section to my post. I will try what you've suggested in your updated post and will update you on the outcome. I'll be glad to mark your response as an answer if it worked.