Geeks With Blogs
Frez Phil Fresle's Developer Blog

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();
 

 

Posted on Tuesday, May 18, 2010 1:20 PM | Back to top


Comments on this post: Back Button issue after Logout in ASP.NET

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by Nitin on Jun 22, 2010 1:46 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by Varun Sharma on Oct 29, 2010 11:53 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Thank you so much for this valuable infmn........ its really a blessng to me...... thank you........
Left by Ambily on Nov 01, 2010 7:05 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
The user can easily preview the last page by clicking back button twice. ;)
Left by Sherwin on Dec 16, 2010 2:41 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
"The user can easily preview the last page by clicking back button twice."

That is true! Is there no solution with that?
Left by prehistoric on Jan 28, 2011 1:57 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
You will need to set the cache to expire on all the pages you do not want the user to view after logout.
Left by Frez on Jan 28, 2011 7:10 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
This code really works well.
They way to explained to use lines of code is amazing.
Thanks a lot Frez.
You are great.
Left by Purnima on Mar 25, 2011 4:45 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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.
Left by juju on Jun 20, 2011 7:53 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Thank you,
This is very helpful to me
Left by lahirumw on Jun 26, 2011 5:31 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by vaishalil on Jun 30, 2011 11:32 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
help me sir
Left by joginder on Aug 06, 2011 7:05 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
To return back the logout button
Left by mandy puno on Aug 10, 2011 12:31 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Thanks for the post.It helped me a lot....
Left by Sree on Aug 22, 2011 8:10 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Hi !
Thanks , it finely works for me.... :)
Left by Sameer on Nov 16, 2011 9:49 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
thnx a lot it was very helpful for me
Left by marwa on Nov 28, 2011 5:33 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by venkat on Jan 26, 2012 8:48 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
favulous ,awesome, i helped me a lot!thanks once again .i am using mozila 9.0 and it works there
Left by creepyman on Feb 02, 2012 1:42 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Fabulous post. This saved me a huge time.
Kudos!
Left by Ranjan on Feb 18, 2012 2:00 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Hello sir
Its great ur code is properly working thanks.
Left by Jitendra Malik on Mar 03, 2012 12:29 PM

# re: i need to calculate time after Logout in ASP.NET
Requesting Gravatar...
i need to calculate time between login and logout in asp.net using c#
Left by selvi on Apr 04, 2012 1:38 PM

# Problem: when i logout, and press back button, it goes back to previous page ASP.NET
Requesting Gravatar...
Plz help
Left by Nadeem Akhtar on Apr 20, 2012 4:58 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
It really worked out for me. It's a great help for a beginner like me.
Left by Robert on Apr 26, 2012 4:28 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
thanks, helped a lot.
Left by Chris on May 23, 2012 12:16 AM

# so kind of you
Requesting Gravatar...
back button issue ofter logout
Left by anees ahmad(lko) on Jun 02, 2012 5:18 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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......
Left by PUVANARAJAN on Aug 01, 2012 12:32 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Hi... Thanks a lot for a wonderful Tip...Wish You All The Very Best
Left by Bhavanarayana Vempati on Oct 06, 2012 12:53 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
thanks 4 ds post.. it work 4 me.:)
Left by aana on Nov 22, 2012 10:14 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Not working yaar.showing resource not found.
Left by shiva on Mar 08, 2013 12:37 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Thank you
Left by Sandesh on Apr 14, 2013 7:00 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
thnk u thank u sooooo much its works...after so many googling..thnks man...
Left by SIDDHI on Apr 15, 2013 6:32 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
amazing it worked thnx alot
Left by marwa on May 06, 2013 8:28 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
i have a problem with this code that is it show..
The name 'FormsAuthentication' does not exist in the current context.
Left by sandeep mishra on Jun 17, 2013 7:32 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
Thanks a lot for a wonderful Tip..It's work 4 me.:)
Left by Tejas Mirani on Dec 10, 2013 7:36 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
very nice article.....
Left by huda on Dec 26, 2013 7:01 AM

# Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by Ashraf on Jan 06, 2014 12:31 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by Mohit on Jan 11, 2014 10:13 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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.
Left by Anant Kotkar on Feb 27, 2014 9:14 AM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
after spending complete day and try many alternative this is perfect solution , thank you very much frez , keep posting like this.
Left by khalid sultani on Apr 26, 2014 4:05 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
very simple and helpful stuff
Left by naga on Aug 08, 2014 10:56 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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.
Left by Bao on Oct 15, 2014 7:43 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
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
Left by Bao on Oct 16, 2014 7:58 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
no no any idea
Left by no no any idea on Dec 17, 2014 2:20 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
thnx this code n site very heLpfuL !!! :-)
Left by Nono on Mar 06, 2015 2:23 PM

# re: Back Button issue after Logout in ASP.NET
Requesting Gravatar...
help me lot
Left by jayakanthan on May 07, 2015 12:12 PM

Your comment:
 (will show your gravatar)


Copyright © Frez | Powered by: GeeksWithBlogs.net | Join free