5

I'm using flask_form in my Flask application and have being stucked for hours now with the 'CSRF Token do not match'.

<form method="post" action="{{ url_for('auth.login') }}" role="form">
    {{ form.hidden_tag() }}
    {{ wtf.form_errors(form, hiddens="only") }}
    {{ wtf.form_field(form.email)}}
    {{ wtf.form_field(form.password)}}
    <p><button type="submit">Login</button></p>
</form>

views.py

@auth.route('/login', methods=['GET', 'POST'])
def login():

    form = LoginForm()
    if form.validate_on_submit():

        print('login form received on server and is valid')
        # check whether user exists in the database and whether
        # the password entered matches the password in the database
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data) and check_password_hash(user.pwd, form.password.data):
            # log employee in
            login_user(user) #,remember=True)

            # redirect to the home page after login
            return redirect(url_for('grapher.upload'))

        # when login details are incorrect
        else:
            flash('Invalid email or password.', 'info')

    # load login template
    return render_template('auth/login.html', form=form, title='Login')

Form

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email(),    Length(min=1,max=254, message='The maximum length of this filed is 254 characters')])
    password = PasswordField('Password', validators=[DataRequired(), Length(max=20, message='Password maximium length is 20 characters.')])

Why do I get this error?

user7924113
  • 169
  • 1
  • 3
  • 15
  • Please post your whole error message – Nabin Sep 12 '17 at 09:27
  • please add you error and the code where you initialise the token – Espoir Murhabazi Sep 12 '17 at 09:56
  • The only error message I get is a "CSRF tokens do not match" under my form. How could I get a more relevant error message? I'm not using CSRF extension but just wtf_form (according to the docs: "Any view using FlaskForm to process the request is already getting CSRF protection") – user7924113 Sep 12 '17 at 10:12
  • @Nabin Any idea? – user7924113 Sep 13 '17 at 13:34
  • @EspoirMurhabazi, I am having the same problem and I have the `form.hidden_tag()` in the template. What do you mean by `the code where you initialise the token`? Do I need to explicitly initialise the token somehow? –  Nov 06 '18 at 18:11
  • I have very similar code as yours and ran into the same problem yesterday. The weird thing is my application had been running for several years without any problems until yesterday when I moved it to a different sub-domain. It took me several hours before I managed to fix it. After tweaking around, it turned out that a browser add-on on Firefox tampered with the csrf_token. After disabling these add-ons (could be Enhancer for Youtube or Youtube Download Plus) and restarting Firefox, everything is back to normal. – Toàn Nguyễn May 08 '20 at 04:01

5 Answers5

7

I was running into the same problem and I just figured out what was happening: cookies! Clearing my cookies for the site fixed the problem immediately.

user697576
  • 780
  • 1
  • 9
  • 11
  • Thanks! I just tried again in an incognito window. Success! – Carlos Hanson Jun 16 '20 at 20:25
  • This solved the issue for me. I installed pgadmin4 which worked fine. Then I added HTTPS, and while I could log in fine, I couldn't really use it until I cleared the cookies. – Paschover Oct 09 '20 at 02:45
2

You need to add a CSRF input field in your form as said in the docs:

<form method="post">
  {{ form.csrf_token }}
</form>

Every WTForms validation checks availability of this token in POST request data unless it is explicitly disabled.

Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
2

I found out that one of the reasons is APPLICATION_ROOT not set correctly.

Knowing how much time can debugging of "the CSRF tokens do not match" error consume, I'm posting this partial answer.

VPfB
  • 14,927
  • 6
  • 41
  • 75
0

For me, in case anyone is experiencing this issue in production, Cloudflare which manages traffic has a caching mechanism. Putting the site into 'development mode' temporarily whilst you navigate pgadmin solved the issue.

Wick 12c
  • 133
  • 2
  • 15
0

Try

app.config["WTF_CSRF_ENABLED"] = False
  • 3
    Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Jul 14 '23 at 11:01