14

How can i stop the back button after user has logout ? (LOGOUT button is in master page) Using webforms

I have few pages, the last page is the final page and after log out when i click back button its showing the previous page.How do i avoid this.Pls help me with the code

Code needs to trigger only after LOGOUT .The user must be able to go back n see previous page if he has to make any changes while he's loged in.

Challa Jyothi
  • 221
  • 1
  • 3
  • 12
  • Are you using `Webforms` or `MVC` ? My thought on this would be to check if the user is logged in or not on the pages you want to secure (such as this 'previous page'). The link in @PatrickHofman answer leads to a result saying **Back button history is not a cache** – TheGeekZn Feb 21 '14 at 09:45
  • **[Check this out](http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript).** It might help. – Bhavik Feb 21 '14 at 10:27
  • @Bhavik anyone can disable Javascript... – TheGeekZn Feb 21 '14 at 10:52
  • @NewAmbition even this can be done using **back-end code** like this `Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.Now);` and/or **html codes** like this ` `.. But javascript is the most feasible option.. – Bhavik Feb 21 '14 at 11:02

8 Answers8

20

You should set the correct HTML headers. According to this these are the ones that work on all browsers:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

You can set them like this:

HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Expires", "0");
Community
  • 1
  • 1
Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294
0
function preventBack(){window.history.forward();}
  setTimeout("preventBack()", 0);
  window.onunload=function(){null};
Jero
  • 61
  • 7
0
<script>
  function preventBack(){window.history.forward();}
  setTimeout("preventBack()", 0);
  window.onunload=function(){null};
</script>

it may work for you

Chirag Sutariya
  • 339
  • 1
  • 11
0

This Approach will only work with MVC sites

This is the approach i use

Add the following filter to your FilterConfig (Assume you are using MVC)

 filters.Add(new System.Web.Mvc.AuthorizeAttribute());

Now decorate the action methods users can use without being logged in with

 [AllowAnonymous]

Be sure to decorate you Login and register methods.

Now when a user clicks back (assuming the page refreshes) they will be asked to login again. I don't allow my pages to be cached forcing refresh on back button.

Hope this helps you a little

KevDevMan
  • 670
  • 9
  • 22
  • the OP didn't say that they were using MVC as opposed to webforms, please update your answer once that is established. – jacqijvv Feb 21 '14 at 09:48
  • 2
    The OP did not say they were not using MVC. Also i state in my answer that i am assuming they are. so if they are not using MVC they can ignore my answer. – KevDevMan Feb 21 '14 at 09:51
0

Perfectly working even when back button is pressed in the browser (tested in crome)

I used a session variable and also I disabled the cache

page 1(default.aspx) login form where I collect the session variable ID

Session["id"] = TextBox1.Text;// just the username</pre>

     page 2(Default2.aspx) in page load 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            Response.Cache.SetNoStore();

                if (Session["id"] == null)
                {    

                    Response.Redirect("Default.aspx");// redirects to page1(default.aspx)

                }
                else
                {
                    Label1.Text = (string)Session["id"];//just display user name in label

                }

        }

In page 2 log out button

     protected void Button1_Click(object sender, EventArgs e)
        {
            Session["id"] = null;

            Response.Redirect("/WebSite5/Default.aspx");//redirects to page1(default.aspx)
        } 
rorra
  • 9,213
  • 3
  • 34
  • 59
0

Tried lot of solutions but only the below one worked out . Added below java script in the logout page. All the other solutions will work fine in browsers other than IE

window.onunload = function() {
                window.location.href = "<%=request.getContextPath()%>/logout.jsp";
            };
Renosh
  • 1
  • 1
0

I know this is an old thread, but someone might help this. You can prevent the back button by using javascript event windows.hash change.

    <script>
        var history_api = typeof history.pushState !== 'undefined';
        if (location.hash == '#no-back') {
            if (history_api) history.pushState(null, '', '#stay')
            else location.hash = '#stay'
 
            window.onhashchange = function () {
                if (location.hash == '#no-back') {
                    alert('Action cannot be done!');
                    if (history_api) history.pushState(null, '', '#stay')
                    else location.hash = '#stay'
                }
            }
        }
</script>

You can visit here for the complete tutorial

Eirik H
  • 534
  • 1
  • 6
  • 25
CET
  • 1
0

Try this i find this best way to prevent back. Got this solution in codeproject.

clean the session value while logout with those common methods.

Session.Abandon();
Session.Clear();
Session.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("frmLogin.aspx", false);

On ASPX page, I use the Jquery with JSON and check the Session value with LogoutCheck() WebMethod.

<script type="text/javascript">
    $(document).ready(function () {
        CheckingSeassion();
    });
    function CheckingSeassion() {
        $.ajax({
            type: "POST",
            url: "frmLogout.aspx/LogoutCheck",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d == 0) {
                    window.location = '<%= BaseURL %>' + "frmLogin.aspx";
                }
            },
            failure: function (msg) {
                alert(msg);
            }
        });
    }

The LogoutCheck() WebMethod checks the session value from application server on client side loading moment.

I created this method on frmLogout.aspx page like this:

[WebMethod]
public static int LogoutCheck()
{
   if (HttpContext.Current.Session["user"] == null)
   {
      return 0;
   }
   return 1;
}

Now, when user logs out the page, it redirects to logout page and clears and abandons the session values. Now when user clicks back button of browser, the client side only loads and in that period the CheckingSession() WebMethod fires in JQuery and it checks the session value LogoutCheck() WebMethod. As the session is null, the method returns zero and the page redirects again in login page. So, I don't have to clear the cache or clear any history of user's browser.

Raghubar
  • 2,710
  • 1
  • 18
  • 27