CSRF Token Error when using gunicorn and Flask - flask

I've developed a web app that includes the functionality for users to log in and signup. I've done everything as per documentation and tutorials, and everything works fine with the flask server.
The issue is: I use gunicorn and start a web server, open the address (localhost:8000) on few different browsers (Brave and Firefox on Linux, and Brave on Android), I can only log in (Single or multiple different users) from only one client. When I try to do so from another one, it throws 400 Bad Request (CSRF Session token missing or CSRF Session tokens do no match).
Now, this doesn't happen when using Flasks Server. It only happens while using gunicorn.
I've deployed the application to Heroku (Using the Free plan), and I want multiple users to sign in at the same time. This happens on all of the other forms my app has.
All environment variables, secret keys are correctly configured, everything works as intended when using Flask Server. Using Gunicorn doesn't cause any other issues except this. Sometimes, logging in from a single client doesn't work too.
Any help would be appreciated. I've already looked at other threads/questions that were related, but they didn't mention the problem I have

Sorry for the late reply (Maybe it can help someone in the future)
The short answer :
use :
with app.app_context():
your code
instead of :
app.app_context().push()
which is never closed
The long answer :
I guess you use Flask-WTF for managing CSRF,
If yes, there is an if bloc (https://github.com/wtforms/flask-wtf/blob/0.15.x/src/flask_wtf/csrf.py#L53) in the generate_csrf function, which check the flask g variable before generating a new CSRF token. It works perfectly, but when the g variable doesn't reinitilize on each new request (see below for the cause) it creates a conflict between the different users trying to log in.
The principal cause of not reinitilizing the flask g variable is an app context which is pushed manually (usually by : app.app_context().push()) but not closed, in this case the app context is never torn down see : Flask app.teardown_appcontext not being called when DEBUG is false
Finally, i think there is something in the flask DEBUG mode, which force tearing down the app context and reinitilize the g variable.

Related

Cookies when using separate Dyno for react frontend and Django backend

I am building a simple web app using React.js for the frontend and Django for the server side.
Thus frontend.herokuapp.com and backend.herokuapp.com.
When I attempt to make calls to my API through the react app the cookie that was received from the API is not sent with the requests.
I had expected that I would be able to support this configuration without having to do anything special since all server-side requests would (I thought) be made by the JS client app directly to the backend process with their authentication cookies attached.
In an attempt to find a solution that I thought would work I attempted to set
SESSION_COOKIE_DOMAIN = "herokuapp.com"
Which while less than ideal (as herokuapp.com is a vast domain) in Production would seem to be quite safe as they would then be on api.myapp.com and www.myapp.com.
However, with this value set in settings.py I get an AuthStateMissing when hitting my /oauth/complete/linkedin-oauth2/ endpoint.
Searching google for AuthStateMissing SESSION_COOKIE_DOMAIN yields one solitary result which implies that the issue was reported as a bug in Django social auth and has since been closed without further commentary.
Any light anyone could throw would be very much appreciated.
I ran into the exact same problem while using herokuapp.com.
I even posted a question on SO here.
According to Heroku documentation:
In other words, in browsers that support the functionality, applications in the herokuapp.com domain are prevented from setting cookies for *.herokuapp.com
Heroku blocks cookies from frontend.herokuapp.com and backend.herokuapp.com
You need to add a custom domain to frontend.herokuapp.com and backend.herokuapp.com
The entire answer https://stackoverflow.com/a/54513216/1501643

Error possible XSRF attack in GWTP application

I have a GWTP application (app1) calling another GWTP application (app2). The first sets a SecurityCookie as the second one.
If app1 is on new session, and this opens app2, everything works. If I close my browser and turn on app1 in new session without wiping the browser cache, app1 calls app2 and prints the following error:
SEVERE: Cookie provided by RPC does not match request cookie, aborting
action, possible XSRF attack. (Maybe you forgot to set the security
cookie?)
Without more info it's hard to provide an exact solution, but this is a known issue in GWTP, because the RandomSecuritySessionFilter changes the cookie each time a new RPC request is issued.
See this github issue here. It's rather long but worth the read if you want to understand the problem.
In my own app I dispatch about 5 async RPC calls at once and kept getting the same error as you in development mode, but much more rarely in production (due to the development server being so fast that calls return in a much more random fashion). So as a hack I turned off the cookie in development mode because it was making my life so difficult.

Thinktecture IdentityModel token rejected

My Durandal SPA app performs BASIC authentication to acquire a session token which it then presents in headers to access Web API controller methods. This works fine.
On successful authentication I cache the access_token in localStorage so I can re-acquire it from local storage to preserve the session in the event of browser closure or refresh. The token is re-acquired but it is rejected by the server with an Unauthorized message.
This question starts by saying that the OP has successfully done what I am trying to do, so it's certainly possible, but the code he shows is a sample of (unsuccessfully) trying to do cookie mapping and I can't divine the nature of my problem from it.
One of the answers to this question says
Fortunately, WIF has a way to mitigate [replay attacks]. By configuring:
<identityConfiguration>
.......
<tokenReplayDetection enabled="true" />
.....
</identityConfiguration>
I do in fact have WIF installed on my development workstation, but I wouldn't know where to start looking for this setting. A search of my HDD found "tokenReplayDetection" in 17 System.IdentityModel related DLLs, but not in any config files.
Does anyone think this is in fact the problem and if so where does it live? Any other thoughts also gratefully received.

Django login stops working randomly

Env:
Django 1.42
Nginx
Gunicorn + gevent
HTTPS
Session storage is default
For some reason login stops working without any reason for some clients on different OS/browsers. Auth is passing, but after redirect user.is_authenticated is False again.
I think, the problem is unrelated to client.
Any ideas why?
It sounds like Django user sessions are getting messed up somehow. Try switching your session engine and make sure your session engine is not running off of a dummy caching backend. If it is running off of a caching engine, make sure your cache isn't being restarted/flushed somehow. Lastly, try using a cookie session backend.

Facebook Connect not setting cookies

I'm trying to implement Facebook Connect on a website with .NET MVC using C#.
I've followed the instructions here: http://wiki.developers.facebook.com/index.php/Trying_Out_Facebook_Connect step by step. I can make the login work as in that when I log in through the site I'm also logged into Facebook.
In order to work with this in the server I think I need to access the cookies Facebook is supposed to leave like:
APIKEY_user
APIKEY_session_key
...
as mentioned here http://wiki.developers.facebook.com/index.php/Verifying_The_Signature.
The thing is I'm not getting any of these cookies. I've googled and it seems like I'm the only person with this problem. Any ideas as to what I could be doing wrong ? Has this happened to anyone else ?
The issue was that I was developing locally using localhost.
I resolved the problem by changing the settings for the application to point to a certain web address instead of localhost and changing my hosts file lo point that same web address to 127.0.0.1
from the UI/client-side perspective, always insure you have the correct path indicated for the xd_receiver file in your FB.init() method.
Firecookie is very useful for seeing what Cookies are/aren't being set.