In my projects __init__.py I have this:
app = Flask(__name__)
app.config.from_object('config')
CsrfProtect(app)
db = SQLAlchemy(app)
My development config file looks like:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
WTF_CSRF_ENABLED = True
SECRET_KEY = 'supersecretkey'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'project.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
And in my unittest setUp I have this:
from project import app, db
class ExampleTest(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
self.app = app.test_client()
db.create_all()
In theory, setting WTF_CSRF_ENABLED to False here should prevent CSRF for the unit tests, however I'm still getting CSRF errors if I do a POST while unit testing. I think it is because I have already called CsrfProtect(app) while WTF_CSRF_ENABLED is True (when I import app, it is called). If I set WTF_CSRF_ENABLED = False in the config file, it works as expected.
Is there anyway I can disable CSRF after it has already been enabled? Or am I barking up the wrong tree here?
Looking at the code for csrf_protect, it checks app.config['WTF_CSRF_METHODS'] every time a request comes in to see if this request type should be CSRF protected. By default the protected methods are:
Because it actually checks the app.config every time, simply changing this to an empty list in my unit tests setUp resolves the issue:
Alternetly, it does register the csrf protection with app.before_request(), so I think it may be possible to unregister it by modifying the before request functions. But I think going that route would be more likely to see problems on future updates.
It wasn't too hard to keep the
csrf_token
if that is an option. I was able to successfully log into an application that used acsrf_token
using some regular expressions and using the login function that is found in the Flask docs about testing.So what I have done here is made the
csrf_token
be apart of the second capture group. This could easily be used to find a token all over the application.You can disable it using the config variable
WTF_CSRF_ENABLED
,for example
or
app.config['WTF_CSRF_ENABLED'] = False
See also flask-WTF documentation