3

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?

jps
  • 20,041
  • 15
  • 75
  • 79
jolynice
  • 514
  • 1
  • 8
  • 25

2 Answers2

7

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.

  • 3
    Please note if you want to promote your own product/blog you **must disclose your affiliation**, otherwise your answer may be flagged as spam. Please read [How to not be a spammer](https://stackoverflow.com/help/promotion) – DavidPostill Aug 04 '17 at 17:10
1

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

coder
  • 8,346
  • 16
  • 39
  • 53
Shashank
  • 11
  • 2