0

Now I am trying to develop server using nginx + unicorn + flask.

If I execute python only, csrf_tokens work without any problems.

However, if I execute python using nginx + unicorn + flask, the error occurs.

400 BAD Request - The CSRF session token is missing. or The CSRF tokens do not match.

Is there additional settings that I should have done for nginx for session?

or Did I miss something??

app/init.py

from flask_wtf.csrf import CsrfProtect

csrf = CsrfProtect()

def create_app(config_name):
   app = Flask(__name__, instance_path='/instance')
   app.config.from_object(config[config_name])
   config[config_name].init_app(app)

   bootstrap.init_app(app)
   moment.init_app(app)
   csrf.init_app(app)
   app.config.update(CSRF_ENABLED = app.config['CSRF_ENABLED'])

   //CSRF_ENABLED = True

   return app

login.html

<form action="{{url_for('.login')}}" class="form-signin text-center" method="POST">
    {{ form.csrf_token }}
</form>
Pooh
  • 71
  • 1
  • 5

1 Answers1

0

I often use in my projects the combination of flask + gunicorn + nginx. For my forms I use a different approach:

form.py:

from wtforms import StringField, SubmitField, IntegerField
from wtforms.validators import DataRequired, Optional

class IdentityForm(FlaskForm):
    age = IntegerField("Type your age", validators=[Optional()])
    name = StringField("Type your name*", validators=[DataRequired()])
    submit = SubmitField("Submit")

page.html

 <form action="" method="post" novalidate>
     {{ form.hidden_tag() }}

     {{ form.age.label }}<br>
     {{ form.age() }}

     {{ form.name.label }}<br>
     {{ form.name() }}

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

In this small example the part that concerns us here is the argument form.hidden_tag() on the HTML's side. This argument generates a hidden field that includes a token that is used to protect the form against CSRF attacks. For this to work it is necessary to define the variable SECRET_KEY in the flask configurations:

SECRET_KEY = os.environ.get('SECRET_KEY') or 'do-not-get-tired-youll-never-find'

The SECRET_KEY is a cryptographic key that makes it possible to generate signatures or tokens. FLASK_WTF use it to protect forms against CSRF attacks.

And that's all. FLASK_WTF takes care of the rest for you

To learn more take a look at this

Tobin
  • 2,029
  • 2
  • 11
  • 19