2017-09-12 67 views
2

我在我的Flask應用程序中使用了flask_form,並且因'CSRF令牌不匹配'而被暫停了幾個小時。Flask_form:CSRF令牌不匹配

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

形式

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

爲什麼我得到這個錯誤?

+0

請發佈您的全部錯誤信息 – Nabin

+0

請將您的錯誤和代碼初始化令牌 –

+0

我得到的唯一錯誤消息是我的窗體下的「CSRF令牌不匹配」。我怎麼能得到更相關的錯誤信息? 我沒有使用CSRF擴展,只是wtf_form(根據文檔:「任何使用FlaskForm處理請求的視圖已經獲得CSRF保護」) – user7924113

回答

0

您需要在您的表單中添加一個CSRF輸入字段作爲docs說:

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

此令牌在POST請求數據的每一個WTForms驗證檢查可用性,除非它是explicitly disabled

0

設置

WTF_CSRF_ENABLED =假

在燒瓶中的配置解決了這個問題對我來說。

+0

是的,因爲你禁用了CSRF保護,如果你需要安全性,這是一件壞事。 – Doaa