how to automatically redirect to a page when the session has timeout?

winanjaya 146 Reputation points
2023-03-04T06:16:58.2533333+00:00

I have a session timeout page, but I don't have an idea on how to automatically redirect to a page when the session has timeout?

program.cs

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.LoginPath = "/User/Login";
    options.ReturnUrlParameter = "ReturnUrl";
    options.AccessDeniedPath = "/User/Login";
    options.LogoutPath = "/User/Logout";
    options.SlidingExpiration = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(AppSettings.Application.SESSION_TIMEOUT);
    options.Cookie.MaxAge = options.ExpireTimeSpan;
});

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,794 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jerry Fu - MSFT 981 Reputation points Microsoft External Staff
    2023-03-06T09:33:15.03+00:00

    Hi @winanjaya ,

    Using cookie authentication in this way won't do anything about using sessions on the server. So your problem is more like "cookie timeout", not "session timeout".

    Normally, using "options.LoginPath" is enough, it will redirect to a url when user request a page if the cookie has expired.

    If you want it redirect to a page without any user request, only on the event of cookie expire, you have to use JavaScript to check cookie status periodically to achieve that. That is because codes running on server cannot automatically send message to browser except you are using some websocket technique.

    You can add this javascript in any razor view page. It will check if a specifc cookie name doesn't exist(expired), it will redirect to some URL. Alternatively, you can save it to js file and make a reference in every page.

    
    @section scripts{
            <script type="text/javascript">
    
                function getCookie(name) {             //a function you can use to get cookie by name
                    var dc = document.cookie;
                    var prefix = name + "=";
                    var begin = dc.indexOf("; " + prefix);
                    if (begin == -1) {
                        begin = dc.indexOf(prefix);
                        if (begin != 0) return null;
                    }
                    else {
                        begin += 2;
                        var end = document.cookie.indexOf(";", begin);
                        if (end == -1) {
                            end = dc.length;
                        }
                    }
                    // because unescape has been deprecated, replaced with decodeURI
                    //return unescape(dc.substring(begin + prefix.length, end));
                    return decodeURI(dc.substring(begin + prefix.length, end));
                }
                function CheckCookie() {
                    var myCookie = getCookie(".AspNetCore.Cookies"); //check if browser has the specific cookie name 
                    if (myCookie == null) {
                        window.location.href = "https://www.microsoft.com/";  
                    }                    
                }
    
                var myVar;
                $(document).ready(function () {                       
                    myVar = setInterval("CheckCookie()", 60000);  //excute checkcookie every 60s
                });
            </script>
        }
    

    Don't forget below code to make document.cookie to work.

    options.Cookie.HttpOnly = false;
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

     

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Jerry Fu

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 29,946 Reputation points
    2023-03-04T11:42:51.2733333+00:00

    Use a JavaScript timer that is set to the same timeout period as the authentication cookie. Then do a window.location = 'http://domain.com' to redirect.

    JavaScript Timing Events

    Or use create a meta refresh with the same timeout period as session.

    HTML <meta> http-equiv Attribute

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.