11

I am using FormsAuthentication for userlogin. I am having a problem after user logs out successfuly the back button is browser allows user to view pages. I tried using javascript

 <script type = "text/javascript" >
        function preventBack() { window.history.forward(1); }
        setTimeout("preventBack()", 0);
        window.onunload = function () { null };
</script>

But back button is completly disabled. It worked bt,I dont want to disable back button functionality when user is logged in. i want my LOGGED IN user to use browser back button as normal. But once he choosed to log out, he is not allow to see any of contents by pressing Back. I also tried using

Session.Abandon();
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.Cache.SetExpires(DateTime.Now);

But this is also not working.how do I fix this?

S.p
  • 1,059
  • 3
  • 15
  • 27
  • I suspect this would be a bad idea, since the user could just disable javascript and then press the back button. – samfrances Jan 21 '13 at 12:03

9 Answers9

18

You could clear the browser history when the user logs out:

var url = window.location.href;
window.history.go(-window.history.length);
window.location.href = url;

However this would not be particularly robust - it relies on javascript, it would not work across multiple tabs and may only serve to annoy the user. IMO the best bet is to set appropriate caching headers such that the browser will not cache any of your 'logged in' pages via a NoCacheAttribute applied appropriately:

public class NoCacheAttribute : ActionFilterAttribute
{  
  public override void OnResultExecuting(ResultExecutingContext filterContext)
  {
      filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
      filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
      filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
      filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
      filterContext.HttpContext.Response.Cache.SetNoStore();

      base.OnResultExecuting(filterContext);
  }
}
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • how do we use this ? Can you give an example How do I call this in a logout method ? def /logout.html end – codeObserver Jun 22 '13 at 00:49
  • 1
    @codeObserver have a look at http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs for an introduction to ActionFilters. NB this approach would not be appropriate for requests that bypass the ASP.Net MVC processing pipeline (eg for static files). – Rich O'Kelly Jun 24 '13 at 10:53
  • @RichO'Kelly I am using this over my Logout action method but it is not working and my method just clears the session and redirects to home page – Mohit Shah Mar 03 '16 at 17:51
  • @RichO'Kelly I have made it work and the action filter is getting executed but still after pressing back button i can access the previous page so i don't think the cache is getting cleared – Mohit Shah Mar 04 '16 at 04:43
  • @mohit Apologies for delay - missed your comments. The attribute needs to be applied to all the pages that are only accessible whilst logged in - applying it when the logout action is executed will have no effect. – Rich O'Kelly Apr 28 '16 at 13:34
  • @RichO'Kelly Is there anyway to clear the cache while logging out – Mohit Shah Apr 28 '16 at 13:35
  • @mohit Not easily. Browsers cache things according to the HTTP headers that are in the response to a request. Those requests and responses have already been and gone by the time the user clicks logout. – Rich O'Kelly Apr 28 '16 at 15:08
9

Use this code in the html page on which you need to control the back button.

$().ready(function() {
    if(document.referrer != 'http://localhost:8181/'){ 
        history.pushState(null, null, 'login');
        window.addEventListener('popstate', function () {
            history.pushState(null, null, 'login');
        });
    }
});

This code will block back button event. The if condition is for allowing the back button if the previous page is 'http://localhost:8181/'. Back button won't be working if the previous page is not 'http://localhost:8181/'. If you need to block all previous pages then avoid the if condition. The history.pushState statements will replace the url on the browser address bar to 'login'. So I recommend you to change 'login' with your page url.

Advantages of this method:-

  1. No need to control the cache.
  2. We could allow the back button event for specified previous pages and could block the rest.

Hoping my answer will help someone.

Arjun Ajith
  • 1,850
  • 5
  • 21
  • 46
6

Disabling back button is not a right way to achieve your need. Instead you can add the following three tags in your html file, which takes care of clearing cache.

<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">
surendran
  • 478
  • 1
  • 8
  • 19
  • in which html we have to put this one? – vishnuprasad kv Nov 23 '16 at 13:52
  • Inside a html file which you don't want to cache. But if you are looking for a way not to cache any file at all, then you should update your server configuration to not to cache[in http header]. – surendran Nov 23 '16 at 15:18
  • is it possible to do it like that, when we reach a particular page, all cache should be deleted. like when we reach login page, all cache should be deleted. – vishnuprasad kv Nov 24 '16 at 04:34
  • Server can control the cache time of the resources its sending to client from no-cache to 5 mins, 1 day, 1 week or according to your need. But forcing the browser to clear its cache is not possible from server side. – surendran Nov 24 '16 at 05:26
3

The easiest way I found is using OutputCache Attribute

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController  : Controller
{
}
Ashwini Verma
  • 7,477
  • 6
  • 36
  • 56
1
 <script language="JavaScript" type="text/javascript">
    window.history.forward();              
 </script> 
shafi7468
  • 323
  • 1
  • 3
  • 15
0

Please go through the article http://www.aspdotnet-suresh.com/2011/11/disable-browser-back-button.html . I used the javacript function provided by the author in my layout page to prevent back button issue , as i need to provide access to certain pages to all visitors of my website.

This solution worked for me in IE 11 and Chrome Version 43.0.2357.130 m.

Hope this helps.

alj
  • 170
  • 10
0
var url = window.history.forward();
window.history.go(-window.history.length);
Poornachander K
  • 603
  • 5
  • 4
0

If you want this for all your pages, you could write in your Global.asax:

protected void Application_BeginRequest()
{
Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Expires", "0");
}

This will not cache any page of your site.

eKek0
  • 23,005
  • 25
  • 91
  • 119
-1

Please use this code in your Master Page Load Event.

if(!IsPostBack)
        {
            if (Session["LoginId"] == null)
                Response.Redirect("frmLogin.aspx");
            else
            {
                Response.ClearHeaders();
                Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
                Response.AddHeader("Pragma", "no-cache");
                            }
        }

Hope it helps! :)

Ain Ronquillo
  • 197
  • 1
  • 3
  • 6