How to prevent browser back button after logout Aspnet Core

不想你离开。 提交于 2020-08-26 06:48:27

问题


I have an aspnet 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?

Best regards.

jolynice


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/44245632/how-to-prevent-browser-back-button-after-logout-aspnet-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!