jolynice
jolynice

Reputation: 544

How to prevent browser back button after logout Aspnet Core

I have an ASP.NET Core web site with cookie authentication. When I logoff, and then, when I click in the back button of the browser, I navigate to the last web page, and I don´t want that, I wan´t the user to be redirect to the login page to be authenticate again.

My startup.cs

public void ConfigureServices(IServiceCollection services)
        {
          ....
            services.AddIdentity<ApplicationUser, ApplicationRole>(
            config =>
            {
                config.User.RequireUniqueEmail = true;
                config.SignIn.RequireConfirmedEmail = true;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/Home/Login";
            })
            .AddEntityFrameworkStores<DbContext>()
            .AddDefaultTokenProviders();
        ......
        }
    

My controller.cs

 public class HomeController : Controller
    {
        .....
        private readonly string _externalCookieScheme;
        ....


        public HomeController(
           .....
            IOptions<IdentityCookieOptions> identityCookieOptions,
            .....)
        {
            ....
            _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
            ....

        }




        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Login()
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> LogOff()
        {
            await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); //don´t remove the cookie
            _logger.LogInformation(4, "User logged out.");
            return RedirectToAction(nameof(HomeController.Login), "Home");
        }       
}

What I am missing here?

Upvotes: 4

Views: 9681

Answers (2)

Shashank
Shashank

Reputation: 11

Make sure that in your Logout action method , you are calling HttpContext.SignoutAsync() method ( using correct overload). After this if you press back button, you will be redirected to login

Upvotes: 1

OpenIDAuthority
OpenIDAuthority

Reputation: 86

You need to set the Cache-Control header. For a single page or controller, you can set the header like this:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

If that doesn't work, make sure the header is not being overwritten. You can find a detailed explanation in my blog post: How To Prevent the Back Button after Logout in ASP.NET Core MVC.

Upvotes: 7

Related Questions