Forums

Flask The CSRF tokens do not match when trying to login

I have a simple authentication on my Flask website with FlaskForm. I can only login on one device without any problems, but when I try to login to another account on another device I get an error: 400 Bad request the CSRF tokens do not match. I have no idea why it happens, should not form.hidden_tag() handle necessary csrf or do I need something else? I have tried adding CSRFProtect with

 <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

added to the form but nothing changes. I have not found any similar issues or solutions. Does anyone know what might be the issue?

The class and login logic:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'my_db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'my_key'
login_manager = LoginManager(app)


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(length=30), nullable=False, unique=True)
    password_hash = db.Column(db.String(length=60), nullable=False)

@app.route('/login', methods=['GET', 'POST'])
def login_page():
  form = LoginForm()
  if form.validate_on_submit():
      attempted_user = User.query.filter_by(username=form.username.data).first()
      if attempted_user and attempted_user.check_password_correction(
            attempted_password=form.password.data
      ):
      login_user(attempted_user)
      return redirect(url_for('main_page'))
   else:
       flash('Username and password are incorrect' category='danger')

   return render_template('endata.html', form=form)

The form:

<form id="login-form" method="post">
  {{ form.hidden_tag() }} {#  csrf already? #}

  {{ form.username() }}

  {{ form.password() }}

  {{ form.submit() }}
</form>

From the flask-wtf docs, that looks like it should work. You can use the developer tools in your browser to look at the hidden field and make sure that it's being included in the page as you expect.