user7924113
user7924113

Reputation: 189

Flask_form : CSRF Token do not match

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?

Upvotes: 5

Views: 13111

Answers (5)

Yash Singhal
Yash Singhal

Reputation: 1

Try

app.config["WTF_CSRF_ENABLED"] = False

Upvotes: 0

Wick 12c
Wick 12c

Reputation: 153

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.

Upvotes: 0

user697576
user697576

Reputation: 827

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.

Upvotes: 7

VPfB
VPfB

Reputation: 17237

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.

Upvotes: 2

Sergey Shubin
Sergey Shubin

Reputation: 3257

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.

Upvotes: 2

Related Questions