Reputation: 183
I am creating a website using flask that requires logging in and out. I am using Flask-Security to help with this. My problem is that after I log out, if I hit the back button, I return to the user's page. Is there a way to prevent returning to a session after logging out by pressing the back button in Flask?
Upvotes: 6
Views: 11685
Reputation: 145
In the file that contains
app = Flask(__name__)
add the following just below it
@app.after_request
def add_header(response):
response.cache_control.no_store = True
return response
That fixed the problem for me.
Upvotes: 1
Reputation: 311
You can tell the browser not to cache any pages by adding the Cache-Control
header after every response. If you only want this for some responses, you could add this to specific views instead.
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
return response
Upvotes: 13
Reputation: 183
Use the Cache-Control
header to prevent a page from being cached.
response.headers.add('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
Upvotes: 2
Reputation: 67509
if I hit the back button, I return to the user's page
This is actually an incorrect statement.
The web browser caches pages locally as the user navigates. If the user logs out and then hits the back button the cached version of the page will be shown. The user will not be returned to the user session, the user session is still closed.
You'll have to trick the browser to avoid this behavior, and this can be hard. For example, if your pages contain only the base layout and then request all the content via ajax when you hit the back button the ajax will find there is no user session in the server and will not show any content.
Upvotes: 5
Reputation: 46320
I don't think this is a Flask related problem. What you can do is redirect the user after the logout. You can do this in Flask with the redirect
method:
from flask import redirect
redirect(url)
Then, if the user presses the back button, it will land on the page where the redirect is located and will get redirected again.
You can also check on each page where a user needs to be logged in if he IS really logged in, then if he's not, do the redirect.
Browsers could cache your pages. When you hit the back button, the browser could show the cached page. To prevent a browser from caching a page, you can set the Cache-Control: no-cache
header. In Flask you can do this by setting the header
attribute of the Response object:
response.headers['Cache-Control'] = 'no-cache'
Upvotes: 1