How to Sign Out a User when Session Expires in AspNetCore

Question: Hello, am trying to implement code that Signs Out a Logged in User when the session expires in Asp.Net Core 6. 
How do you do this?


Please Login to see the rest of the answer

Answer: Follow the Instruction below in order to implement the Automatic #SignOut of Logged in Users when the Session Expires in Asp.Net #Core 6 #MVC application.

1. Add ConfigureApplicationCookie Service to the Dependecy Container in the Startup or Program class.

 

 services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
               // options.Cookie.Name = "YourAppCookieName";
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromSeconds(30);
               //options.LoginPath = "/Identity/Account/Login";
                // ReturnUrlParameter requires 
                //using Microsoft.AspNetCore.Authentication.Cookies;
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration = true;
                // options.ForwardSignOut = "/Identity/Account/Logout";
               //  options.ForwardForbid = "/Identity/Account/Login";
            });

2. Add #Sessions Service to the #Dependency #Container
 

 services.AddSession(options =>
            {
                //options.IdleTimeout = TimeSpan.FromHours(9);
               //options.Cookie.Expiration = TimeSpan.FromSeconds(9); // This throws an error "Expiration cannot be set for the cookie defined by SessionOptions"
                options.IdleTimeout = TimeSpan.FromSeconds(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

3. Add the #UseSession #Middleware in the #Configure function in the startup or #program class in between #UseAuthentication and #UseEndpoints Middlewares.

 app.UseSession();


Troubleshooting:

1. When trying to log out and you experience an error that says "InvalidOperationException: No sign-out authentication handler is registered for the scheme '/Identity/Account/Logout'. The registered sign-out schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies. Did you forget to call AddAuthentication().AddCookie("/Identity/Account/Logout",...)?"

- Go ahead and comment out the code that ForwardsSignOut request to the defined endpoint. This should resolve it.

// options.ForwardSignOut = "/Identity/Account/Logout";

Write an Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.


© 2022 - ErnesTech - Privacy