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

在 Windows 8 上运行的 chrome 浏览器中显示错误。Firefox 不会给出此错误。这是一个烧瓶应用程序,登录表单是使用 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>

无法追踪其他任何内容...form.errors 的打印输出显示了上述 csrf_token 错误。

巧合的是,当我尝试使用相同的 chrome 浏览器登录到 stackoverflow 时,它说第三方 cookie 已禁用....这可能是上述行为的原因吗?任何指针都有帮助...

这是意见:

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

和表格:

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.')
4

1 回答 1

0

尝试替换{{form.csrf_token}}{{form.hidden_tag()}}

我的假设是chrome没有发送隐藏标签的csrf_value。

要检查这个假设是否正确,您需要在发布表单后检查您在 flask.request.form["csrf_token"] 获得的内容。如果你什么都没得到,那么我的假设可能是正确的。

至于可能导致它的原因,我知道在 XHTML 中您不能将 input 元素嵌套在 form element中。这就是为什么 Flask-WTF 有一种特殊的添加隐藏标签的方法,请参阅这个文档页面

于 2013-08-17T13:43:36.693 回答