Phil Fresle's Developer Blog

Back Button issue after Logout in ASP.NET

This is the code most of us would normally use when logging out a user:

FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();


A frequent problem is that after a user logs out of their application using this code or similar, if they then use the back button they are presented with pages from the application without having to login. The reason that this problem occurs is because the client browser is caching the output from the pages and when the Back button is pressed the page content shown last is displayed directly from the cache without executing the code behind that might otherwise detect the user is unauthenticated and deny access if instead the page had been requested from the server again.

One solution might be to send appropriate headers with every page in the application to ask the browser not to cache the pages. This will work but it will mean that we will have to ensure that the headers are sent with each and every page either by either posting the same code on every page, using master pages or by having a common base class for every page, it will also mean that when the user uses the Back button in our application they will be hitting the server for the page every time rather than retrieving it from their browser cache which may not be desirable for performance reasons.

My solution is to use a half-way house that prevents the back button returning to an authenticated page after logout, when authenticated allows the back button to work as usual in retrieving the page from the browser cache, but has the downside that the user can still choose to access a page from their browser history after logging off as long as it is still in the browser's cache.

The first step is to create a logout.aspx page and have our logout button simply redirect the user to this page. The logout page is going to request that the browser does not cache it and then log the user out of the application.

In the Page_Load event for the logout.aspx page, enter the following code:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Cache.SetNoStore();
 

This code will request that the browser does not cache the page, but this will only occur if the response finishes and the page is displayed, i.e. we cannot simply do a SignOut and RedirrectToLoginPage within the Page_Load event.

The next step is to add an Ajax ScriptManager and Timer to the logout.aspx page as we are going to user the timer's tick event after the page has been displayed for a second to logout and redirect the user. So paste this code into the page (ensuring that you have also included ajax in your project):

<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager> 
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"> 
</asp:Timer>


Then you can code the Timer1_Tick event to logout the user and redirect them to the login page. Unfortunately, we cannot use RedirrectToLoginPage to redirect them as this would have a return url of our logout page, so we will put together our own url so that the user is redirected to index.aspx (you could change the code to redirect to any page of your choosing when the user logs in). Paste this code (or similar) into the Timer1_Tick event of the logout.aspx page:

string redirectUrl = FormsAuthentication.LoginUrl + "?ReturnUrl=index.aspx"; 
FormsAuthentication.SignOut(); 
Response.Redirect(redirectUrl); 


So, when the user clicks the logout button in our application, the logout.aspx page will be displayed, perhaps with a message saying "Logging out…", for a short period depending on what we have decided is a suitable interval (I use 1 second), and then the user is redirected to the login page. The user will now find that the Back button does not work and when they login they are redirected to the index page.

This solution still has an issue raised by some posters below, and that is if the user clicks the back button multiple times they will be able to get to the old pages, also, the Opera browser does not appear to respect the instructions we pass not to cache the logout page. A workaround to this is to add the following javascript code to the <head> section of the logout.aspx page:
 

<script type="text/javascript">
 window.history.forward(1);
</script>

This javascript code will forward the user back if the user gets to the logout page by pressing the back button.

Note that, as discussed above, these tips ara a half-way house solution. If you need to ensure the user has no way to get back to the pages after they logout you must ask the browser not to cache any of the pages by including code similar to the following on every page:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Cache.SetNoStore();
 

 



Feedback

# re: Back Button issue after Logout in ASP.NET

Hello Phil.
I also had an issue with the back button problem.I read your blog and followed it.
I did all the things exactly you wrote.
But after these statements I get an error

string returnurl = FormsAuthentication.LoginUrl + "?ReturnUrl=default.aspx"; FormsAuthentication.SignOut();

Response.Redirect(returnurl);

Here default.aspx is my login page.
Error ehich i get is:
Server Error in '/login' Application.
--------------------------------------------------------------------------------

The resource cannot be found.

Error code is 404.It says:
The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /login/login.aspx
Please Help me,I am frustated with ths error.
Please Help me soon.
My mail Id: nitinvincible@gmail.com 6/22/2010 1:46 PM | Nitin

# re: Back Button issue after Logout in ASP.NET

Hi There,

Thank you very much for the article. It helped me to solve the back button issue..

Just wanted to know that what happens when one clicks the back button from the login page after logging out.
Does the browser loads the logout page and redirects to login page after 1 sec due to timer or it just stays to login page?

The reason I asked this question is that , when I click back from login page after logging out, the address bar flickers very quickly but remains in the login page..

thanks
varun 10/29/2010 11:53 AM | Varun Sharma

# re: Back Button issue after Logout in ASP.NET

Thank you so much for this valuable infmn........ its really a blessng to me...... thank you........ 11/1/2010 7:05 PM | Ambily

# re: Back Button issue after Logout in ASP.NET

The user can easily preview the last page by clicking back button twice. ;) 12/16/2010 2:41 AM | Sherwin

# re: Back Button issue after Logout in ASP.NET

"The user can easily preview the last page by clicking back button twice."

That is true! Is there no solution with that? 1/28/2011 1:57 PM | prehistoric

# re: Back Button issue after Logout in ASP.NET

You will need to set the cache to expire on all the pages you do not want the user to view after logout. 1/28/2011 7:10 PM | Frez

# re: Back Button issue after Logout in ASP.NET

This code really works well.
They way to explained to use lines of code is amazing.
Thanks a lot Frez.
You are great. 3/25/2011 4:45 AM | Purnima

# re: Back Button issue after Logout in ASP.NET

logout page is not working. still clicking on back button take it to the previous page. Even my timer event is not working. Can you please see my case. Thanks a lot. 6/20/2011 7:53 PM | juju

# re: Back Button issue after Logout in ASP.NET

Thank you,
This is very helpful to me 6/26/2011 5:31 PM | lahirumw

# re: Back Button issue after Logout in ASP.NET

before logout the page if we clicking on back button on browser its take the user back & then click on forward again take the user to main screen for security reasons

please help me 6/30/2011 11:32 AM | vaishalil

# re: Back Button issue after Logout in ASP.NET

help me sir 8/6/2011 7:05 AM | joginder

# re: Back Button issue after Logout in ASP.NET

To return back the logout button 8/10/2011 12:31 AM | mandy puno

# re: Back Button issue after Logout in ASP.NET

Thanks for the post.It helped me a lot.... 8/22/2011 8:10 AM | Sree

# re: Back Button issue after Logout in ASP.NET

Hi !
Thanks , it finely works for me.... :) 11/16/2011 9:49 AM | Sameer

# re: Back Button issue after Logout in ASP.NET

thnx a lot it was very helpful for me 11/28/2011 5:33 PM | marwa

# re: Back Button issue after Logout in ASP.NET

yea dis really wrks bt ders is one issue afta evry 1sec it gives a refreshing kind of jerk in the website ....y is it happening......hopefully u vll answer my qstn...
THNX in Advance.......
plz do help me out 1/26/2012 8:48 AM | venkat

# re: Back Button issue after Logout in ASP.NET

favulous ,awesome, i helped me a lot!thanks once again .i am using mozila 9.0 and it works there
2/2/2012 1:42 PM | creepyman

# re: Back Button issue after Logout in ASP.NET

Fabulous post. This saved me a huge time.
Kudos! 2/18/2012 2:00 PM | Ranjan

# re: Back Button issue after Logout in ASP.NET

Hello sir
Its great ur code is properly working thanks. 3/3/2012 12:29 PM | Jitendra Malik

# re: i need to calculate time after Logout in ASP.NET

i need to calculate time between login and logout in asp.net using c# 4/4/2012 1:38 PM | selvi

# Problem: when i logout, and press back button, it goes back to previous page ASP.NET

Plz help 4/20/2012 4:58 AM | Nadeem Akhtar

# re: Back Button issue after Logout in ASP.NET

It really worked out for me. It's a great help for a beginner like me. 4/26/2012 4:28 AM | Robert

# re: Back Button issue after Logout in ASP.NET

thanks, helped a lot. 5/23/2012 12:16 AM | Chris

# so kind of you

back button issue ofter logout 6/2/2012 5:18 PM | anees ahmad(lko)

# re: Back Button issue after Logout in ASP.NET

Thank you so much... it is working properly. But i have another doubt. It is work only for the back button. I can use url without using the login. How to solve this problem. It is very urgent. My email id is puvanarajan@gmail.com.

Plz...... 8/1/2012 12:32 PM | PUVANARAJAN

# re: Back Button issue after Logout in ASP.NET

Hi... Thanks a lot for a wonderful Tip...Wish You All The Very Best 10/6/2012 12:53 PM | Bhavanarayana Vempati

# re: Back Button issue after Logout in ASP.NET

thanks 4 ds post.. it work 4 me.:) 11/22/2012 10:14 AM | aana

# re: Back Button issue after Logout in ASP.NET

Not working yaar.showing resource not found. 3/8/2013 12:37 PM | shiva

# re: Back Button issue after Logout in ASP.NET

Thank you 4/14/2013 7:00 AM | Sandesh

# re: Back Button issue after Logout in ASP.NET

thnk u thank u sooooo much its works...after so many googling..thnks man... 4/15/2013 6:32 AM | SIDDHI

# re: Back Button issue after Logout in ASP.NET

amazing it worked thnx alot 5/6/2013 8:28 AM | marwa

# re: Back Button issue after Logout in ASP.NET

i have a problem with this code that is it show..
The name 'FormsAuthentication' does not exist in the current context. 6/17/2013 7:32 AM | sandeep mishra

# re: Back Button issue after Logout in ASP.NET

Thanks a lot for a wonderful Tip..It's work 4 me.:) 12/10/2013 7:36 AM | Tejas Mirani

# re: Back Button issue after Logout in ASP.NET

very nice article..... 12/26/2013 7:01 AM | huda

# Back Button issue after Logout in ASP.NET

I got lot of suggestions but could reach to solve the back button problem after logout but finally got a perfect solution here.
Thank you for such a valuable post 1/6/2014 12:31 PM | Ashraf

# re: Back Button issue after Logout in ASP.NET

I m getting Error in "FormsAuthentication"" as The Name 'FormsAuthentication' does not exist in current contxt.
Plzz tell me hw can i remove this.
Any namespace or any other file plzz help me?? Thnxx
1/11/2014 10:13 AM | Mohit

# re: Back Button issue after Logout in ASP.NET

Thank you Sir, my problem is solved :-).
But if i put the address of previous page in address bar then it was redirect on that page. So please give me solution for that. 2/27/2014 9:14 AM | Anant Kotkar

# re: Back Button issue after Logout in ASP.NET

after spending complete day and try many alternative this is perfect solution , thank you very much frez , keep posting like this. 4/26/2014 4:05 PM | khalid sultani

# re: Back Button issue after Logout in ASP.NET

very simple and helpful stuff 8/8/2014 10:56 PM | naga

# re: Back Button issue after Logout in ASP.NET

Hi,

I've been experiencing a very strange behavior on PROD environment.

Following your tutorial, I make it works on DEV environment. However on PROD environment, the ticker keeps firing... on Chrome, Network tab, I see LogoutPage.aspx, status canceled in a loop. I can't do anything but have to close the browser.

Below is the message in the 'Headers'

Request URL:https://site.com/LogoutPage.aspx
Request Headers
Provisional headers are shown
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Content-Type:application/x-www-form-urlencoded
Origin:https://site.com
Referer:https://site.com/LogoutPage.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:1008F0FA-5726-49CF-876E-CC92AB62CB41
Form Dataview sourceview URL encoded
__EVENTTARGET:ctl00$MainContent$Timer1
__EVENTARGUMENT:
__VIEWSTATE:/wEPDwULLTEwMjE0NDM4MjMPZBYCZg9kFgICAw9kFg4CAQ8PFgIeCEltYWdlVXJsBUVodHRwczovL3NtYXJ0dG9vbHMuc3NpLnNhbXN.....


LogoutPage.aspx
/******************************************************************************/
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
</asp:Timer>
<script type="text/javascript">
window.history.forward(1);
</script>
/******************************************************************************/

LogoutPage.aspx.vb
/**************************************************************************************/
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Master.FindControl("TopMenu").Visible = False
Me.Master.FindControl("LeftMenu1").Visible = False
Me.Master.FindControl("BreadCrumb1").Visible = False

Session.Clear()
Session.Abandon()
Session.RemoveAll()

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()
End Sub

Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
FormsAuthentication.SignOut()
Response.Redirect("~/LoginPage.aspx", True)
End Sub
/******************************************************************************************/

Thank you. 10/15/2014 7:43 PM | Bao

# re: Back Button issue after Logout in ASP.NET

The onTick event caused a redirect looping issue on my PROD environment and I don't know why. I removed the onTick event, put the no cache in master page:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()

It works like a charm.

Thanks 10/16/2014 7:58 PM | Bao