Flask Session will not Persist - python

I have recently deployed my first Flask application (first web application ever actually), one problem I am running into and haven't had luck tracking down is related to sessions.
What I am doing is when the user logs in I set session['user'] = user_id and what is happening is I occasionally get a key error when making a request involving that session key. If I try to make the request again the session key is there and the request works fine. I have done research and set the app.config['SERVER_NAME'] to my domain and made sure the secret_key was static, it was dynamic before.
This does not happen when on my local development server so I am a bit stumped at this point.

Problem was that I had the key static in my init which caused it to work in dev but in production in the .wsgi it was still dynmaic, I have changed this and all seems to be working now.

Related

Bad request (400) on Django Localhost

I have the project successfully deployed through AWS. However, I would like to make some changes and experiment on them using localhost:8000/ first before making the changes to AWS server. I set my settings.py to: ALLOWED_HOSTS = ['IP address', 'www.website.com'] to deploy it. Though, I also want to be able to run the server in my local computer so I can experiment it before showing to public. The url is (r^homepage$') When I go to localhost:8000/homepage, it gives a Bad Request (400). I tried many permutations of the urls but nothing works.
you can set Debug=True to see the error message.

Same Flask login session across two applications

Two separate Flask applications, running on two different subdomains, however the login sessions are not persisting between the subdomains.
For example; logging into a.example.co.uk will result in the user being logged in. However, visiting b.example.co.uk - the user will not be logged in.
Running Apache, Flask (with Flask-Login), Ubuntu 18, Python 3.
App secret is the same on both applications. Tried playing with SERVER_NAME configuration setting.
Cookies are correctly being set to .example.co.uk
Cookies are configured to be used on any subdomain.
SESSION_COOKIE_NAME="example",
SESSION_COOKIE_DOMAIN=".example.co.uk",
REMEMBER_COOKIE_DOMAIN=".example.co.uk",
Logging into either subdomain should mean the user is logged into the other.
Managed to solve it!
Turns out I was setting the Flask application secret keys in the wsgi files, like so;
from App import app as application
application.secret_key = 'xxxxxxx'
And both the applications had different secret keys in their wsgi files! Completely forgot I was setting the secret keys in both the wsgi file and the main python file.
Removing setting the secret keys from the wsgi files solved my problem
Does it remember when you close out and go back into a.example.co.uk? You need to set REMEMBER_COOKIE_SECURE in your config to False or None, can't remember but I had this issue before and that was what solved it. Check out Flask-Login Documentation

Strange session behaviour with a Flask app on Heroku

I have a web application that uses GitHub's OAuth API in order to allow the app's users to interact with GitHub. However, I'm seeing some very odd behaviour with regards to the session cookie.
As a bit of background, I am using peewee to interface with Heroku's Postgres server, and have a User model like so:
class User(peewee.Model):
login = peewee.TextField(unique=False)
token = peewee.TextField()
I am using the web application flow described in the GitHub OAuth documentation, and am successfully getting called back with an access token, which I store in the database, and also in the session [1]:
#app.route('/callback')
def finishlogin():
# I've verified that `token` and `login` are both valid at this point
user = User.create(login=login, token=token)
session['token'] = token
return redirect(url_for('home'))
My route for home is as follows:
#app.route('/')
def home():
if 'token' in session:
user = User.get(token=session.get('token'))
return 'Your login is {}'.format(user.login)
else:
# ...
So far, so good, and this works correctly. However, I am experiencing instances of users logging in, refreshing the page and finding that they are suddenly logged in as someone else. Logging the requests to the app shows that on the second request the session cookie itself has sent the wrong value (i.e. session.get('token') in home() returns a valid, but incorrect value. Clearly the user's browser can't know any other session value, so it seems that there is some "leakage" in setting the session between different clients and requests.
I'm not sure what the problem might be. My database is stored on the Flask g object as described in the peewee docs and has before_request and teardown_request hooks set up to open and close the database connection, and from all the documentation and example code I have read (and I've read a lot!), I seem to be using the session object correctly. I have set up a working secret_key for the session store.
I'm wondering if this could be something going on with Heroku and their routing mesh? But then, how would one user suddenly send another user's session?
Any hints or advice would be appreciated—I've been staring at this for a long time and am at my wits' end.
[1] I'm aware that storing the token directly is a bad design choice. The application is non-public and this will be fixed, but for now I want to describe the problem as it exists, even though it's not ideal.
Answering my own question for future reference.
It seems that this was being caused by Flask's default session cookie behaviour, which is to send a Set-Cookie header with every single request, even for static assets. Our local Squid proxy was therefore gladly caching those requests and re-issuing Set-Cookie headers for every user.
Setting Cache-Control headers for the whole app seems to fix the issue.

How to test Facebook authentication using python social auth in localhost? Edited with more details

The question explains mostly everything. I am writing a Django app which will use Facebook authentication through Python social auth. I created an app using Facebook developers. The thing is, I don't have the domain set up with my website as I am still testing on localhost. I could not put in the localhost URL in the Facebook app settings. When I try to login through localhost, it says the URL must match with the domain.
What to do now? Without testing, I cannot host my website either as I am not sure if everything will work like i want it to.
EDIT:
I created a test app and was able to put localhost:8000 as the site url and localhost as app domain. However, the same problem still exists. It says that the 2 urls has to match or something. NOTE: In my local host, the login is 127.0.0.1:8000/login/facebook. And yes, I did update the ID and the app secret for my test app.
What to do now?
You should be able to create a test app within Facebook (There is a 'Create Test App') menu option. It may be that you need to first create an App, and once you have it, you will be able to create the Test App for it, but for sure you can create a Test App.
On that test app, use http://localhost:8000/ as your local URL. Just make sure it is the exact same URL (i.e. you cannot have 'localhost' on Facebook, but then start the server for '127.0.0.1'). Note that the AppID and AppSecret you will use is of the Test App (not the production app).
This should work. I have not used this for python-social-auth but use this to test with django-allauth, and there is no reason why it will be any different.

flask_login sometimes mixes logins; I'm logged in as somebody else

I'm using the awesome Flask framework to create a website in which I use Flask-login for my user logins. This normally works fine, but sometimes I see strange issues with logins being mixed. We've got 3 flask dev-servers running on one machine (on different ports) and we're working in an office with about 10 people (with one shared ip). The problem is that sometimes one user is suddenly logged in as another user.
I can't really pinpoint when or under which circumstances this happens. But I also don't really know how I can debug it. Could the source of the evil be that we share an internet connection or is the problem that we run several flask dev-servers on one machine?
I don't know whether this also happens with people outside of our office (we're still in testing phase).
Can anybody give me some tips on how I can debug this?
Most likely you are using a web server which is caching (some of ) HTTP replies from Flask. These could include static media, generated media, PDFs, Office files.
A misconfigured front end web server may cache such a HTTP response containing media and the session cookie (Cookies header). After happily caching this response then the front end web server serves it to another user. The existing session cookie of this user gets overwritten with the session cookie from the cached HTTP response. Then, due to session switch, the user becomes the user whose HTTP response was cached.
Solutions
Fix your session middleware
Explicitly set no caching headers on the server side
Configure your front end web server not to cache responses with cookies
Further information in operationssecurity.org.

Categories