3
{csrf_token': [u'CSRF failed']} 

error shows up in chrome browser running on windows 8. Firefox does not give this error. This is a flask app and the login form is made using wtforms.

 <form action="{{url_for('login')}}" name="login" method="post" class="form-horizontal">
  {{form.csrf_token}}
  <h2>{{form_title}}</h2>
  <hr>
  <ul><li class="label">{{form.username.label  }}</li>
    <li class="input">{{render_field(form.username)}}</li>
    <li class="desc">{{form.username.description}}</li>
  </ul>
  <ul><li class="label">{{form.password.label  }}</li>
    <li class="input">{{render_field(form.password)}}</li>
    <li class="desc">{{form.password.description}}</li>
  </ul>
  <ul><li class="label">{{form.remember.label  }}</li>
    <li class="input">{{render_field(form.remember)}}</li>
    <li class="desc">{{form.remember.description}}</li>
  </ul>
  <input type="submit" class="sbutton" value="Log In" />
</form>

Cannot track down anything else ...the printout of the form.errors shows the above csrf_token error.

Coincidentally when I try to login using the same chrome browser to stackoverflow it says third party cookies are disabled....could this be the reason for the above behaviour ? Any pointers are helpful...

here is the views:

class Login(MethodView):
def __init__(self):
    self.form = LoginForm()

def get(self):
    return render_template('login.html',form=self.form,form_title="Login User")

def post(self):
    username = self.form.username.data
    password = self.form.password.data

    log_handle.debug(self.form.data.items())
    if self.form.validate_on_submit():
        qstr = "SELECT * FROM user_account WHERE email='%s'"%(username)
        try:
            cursor.execute(qstr)
        except Exception:
            log_handle.exception("Could not execute:%s"%(qstr))
            flash("Could not log you on. Consult admin")
            redirect(url_for("index"))

        try:
            a = cursor.fetchall()
        except Exception:
            log_handle.exception("Could not fetch of data from:%s"%(qstr))
            flash("Could not log you on. Consult admin")
            redirect(url_for("index"))


        #now create a object understood by the flask-login
  #now create a object understood by the flask-login
        fuser = Login_user(name=a[0]['username'],id=a[0]['id'],active=a[0]['is_active'],user_role=a[0]["role"])

        remember = request.form.get("remember", "no") == "yes"
        if login_user(fuser,remember):
            session['language'] = app.config['BABEL_DEFAULT_LOCALE']
            #set customer type session variables
            a = SessionVar()
            a.set_customer_type()

            flash("Logged in!")
            return redirect(url_for("campaign_mod"))
        else:
            flash("Sorry, but you could not log in.")
    else:
        flash("failed csrf token")
        log_handle.debug(self.form.errors)
        log_handle.debug(self.form.data.items())
        return render_template('403.html'), 403

and the forms:

class LoginForm(Form):
username   = TextField(_(u"Email"),[validators.Required(),validators.Email()],description="use your email as your username")
password   = PasswordField(_(u"password"),[validators.Required()],description="Your password")
remember   = BooleanField(_(u"Remember Me."),default=True,
                                     description=_(u"This will store a cookie so as to restore it when you revisit the site."))
def validate_password(form,field):
    #now check if the username and password are correct combination.
    qstr = "SELECT * FROM user_account WHERE email='%s'"%(form.username.data)
    cursor.execute(qstr)
    a = cursor.fetchall()

    if len(a) > 0:
        hpasswd = a[0]['password']
        if bcrypt.hashpw(form.password.data, hpasswd) != hpasswd:
            log_handle.debug('password did not  match')
            raise ValidationError('cannot find a valid combination of username / password. Please try again.')
    else:
        raise ValidationError('cannot find a valid username. Please try again.')
Paco
  • 4,520
  • 3
  • 29
  • 53
user1102171
  • 624
  • 1
  • 8
  • 21
  • Can you share the code for the login view? – codegeek Jan 07 '13 at 19:07
  • 2
    Try to check if you have settings set correct. Especially SERVER_NAME or others related to cookies. More: http://flask.pocoo.org/docs/config/#builtin-configuration-values – Ignas Butėnas Jan 08 '13 at 07:53
  • I tried today with chrome on ubuntu and that works fine. So it means this is a windows specific problem. .... – user1102171 Jan 08 '13 at 10:57
  • When you look at the rendered html do you see a hidden field with a `tokeny` looking thing in it? When you look in the `POST` in your browser's debugger or a proxy do you see a form encoded field called `csrf` or something similiar? – nsfyn55 May 06 '14 at 04:38
  • possible duplicate of [Flask-WTF - validate\_on\_submit() is never executed](http://stackoverflow.com/questions/10722968/flask-wtf-validate-on-submit-is-never-executed) – nsfyn55 Jun 18 '14 at 00:30

1 Answers1

0

Try replacing {{form.csrf_token}} by {{form.hidden_tag()}}

My hypothesis is that chrome is not sending the csrf_value of the hidden tag.

To check if this hypothesis is right, you need to check what you are getting at flask.request.form["csrf_token"] after posting the form. If you get nothing, then my hypothesis is probably right.

As for what might be causing it, I know that in XHTML you cannot nest input elements within the form element. That is why Flask-WTF has a special way of adding hidden tags, see this doc page.

Community
  • 1
  • 1
Walter Cacau
  • 176
  • 2
  • 2